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?
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.
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.
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).
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.
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.
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.
Now that C++11 is widely adopted, std::shared_ptr
should be preferred to the Boost version. See the dereferencing operators here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With