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

62,752

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.

Share:
62,752
Pavan Dittakavi
Author by

Pavan Dittakavi

Hi There!. I am Pavan, from India. I am interested in becoming a polyglot programmer and to be able to work on any part of the technology stacks - the UIs, the server backbones, messaging queues, the search engines and the databases. Feel free to drop a message should something interests you!. Thanks, Pavan.

Updated on July 13, 2022

Comments

  • Pavan Dittakavi
    Pavan Dittakavi almost 2 years

    I have a query. Can we get the object that a shared pointer points to directly? Or should we get the underlying RAW pointer through get() call and then access the corresponding object?