How to get the Object being pointed by a shared pointer?

Solution 1:

You have two options to retrieve a reference to the object pointed to by a shared_ptr. Suppose you have a shared_ptr variable named ptr. You can get the reference either by using *ptr or *ptr.get(). These two should be equivalent, but the first would be preferred.

The reason for this is that you're really attempting to mimic the dereference operation of a raw pointer. The expression *ptr reads "Get me the data pointed to by ptr", whereas the expression *ptr.get() "Get me the data pointed to by the raw pointer which is wrapped inside ptr". Clearly, the first describes your intention much more clearly.

Another reason is that shared_ptr::get() is intended to be used in a scenario where you actually need access to the raw pointer. In your case, you don't need it, so don't ask for it. Just skip the whole raw pointer thing and continue living in your safer shared_ptr world.

Solution 2:

Ken's answer above (or below, depending on how these are sorted) is great. I don't have enough reputation to comment, otherwise I would.

I'd just like to add that you can also use the -> operator directly on a shared_ptr to access members of the object it points to.

The boost documentation gives a great overview.

EDIT

Now that C++11 is widely adopted, std::shared_ptr should be preferred to the Boost version. See the dereferencing operators here.