The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.
In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.
std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.
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.
Use the get()
method:
boost::shared_ptr<foo> foo_ptr(new foo());
foo *raw_foo = foo_ptr.get();
c_library_function(raw_foo);
Make sure that your shared_ptr
doesn't go out of scope before the library function is done with it -- otherwise badness could result, since the library may try to do something with the pointer after it's been deleted. Be especially careful if the library function maintains a copy of the raw pointer after it returns.
Another way to do it would be to use a combination of the &
and *
operators:
boost::shared_ptr<foo> foo_ptr(new foo());
c_library_function( &*foo_ptr);
While personally I'd prefer to use the get()
method (it's really the right answer), one advantage that this has is that it can be used with other classes that overload operator*
(pointer dereference), but do not provide a get()
method. Might be useful in generic class template, for example.
For std::shared_ptr (C++11 onwards) also, there is a get method to obtain the raw pointer. link
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