Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 275
Pavan Dittakavi Avatar asked Jun 27 '11 11:06

Pavan Dittakavi


People also ask

What does shared pointer get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

What is the use of shared pointer in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

What happens when you move a shared pointer?

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).

Is shared pointer a smart pointer?

Shared pointers in C++ In C++, a shared pointer is one of the smart pointers. The shared pointer maintains a reference count which is incremented when another shared pointer points to the same object. So, when the reference count is equal to zero (i.e., no pointer points to this object), the object is destroyed.


2 Answers

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.

like image 116
Ken Wayne VanderLinde Avatar answered Oct 10 '22 06:10

Ken Wayne VanderLinde


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.

like image 38
jakar Avatar answered Oct 10 '22 07:10

jakar