My question is that what are the various ways in which get() member from the shared_ptr class can be used? And why can't we use delete to delete it?
std::unique_ptr::getReturns the stored pointer. The stored pointer points to the object managed by the unique_ptr, if any, or to nullptr if the unique_ptr is empty.
shared_ptr is also helpful in C++ Standard Library containers when you're using algorithms that copy elements. You can wrap elements in a shared_ptr , and then copy it into other containers with the understanding that the underlying memory is valid as long as you need it, and no longer.
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.
If you had a function taking a raw pointer
void f(T *t); // non-owning pointer
And you had a smart pointer to a T
object, you could pass it to that function by using get()
std::shared_ptr<T> sp{new T}; // or unique_ptr
//f(sp); // no good, type mismatch
f(sp.get()); // passes the raw pointer instead
APIs taking raw pointers are common, and still useful. I'd suggest you watch this part of Herb Sutter's talk from CppCon 2014, and probably the parts around it.
You should not attempt to delete this pointer, the smart pointer classes assume you will not do anything like that, and will still free the managed object in their own destructors when the time comes (after all, how would it know you deleted it?).
The smart pointer's job is to manage the object and delete it at the right time, if you want to manually manage the lifetime of the object (not usually recommended) then use a raw pointer.
If you do want to assume ownership of a unique_ptr
you can do so by calling release()
.
Usually you would use get()
when you need to pass a raw pointer to an API that accepts such a pointer.
The shared_ptr
class manages the ownership of the pointer, so it will automatically delete the owned memory when the lifetime of the smart pointer ends. If you try to delete the memory yourself then when the shared_ptr
tries to deallocate you will wind up with undefined behavior.
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