What is the use of the get () member from the shared_ptr class?

My question is, what are the different ways to use the get () member from the shared_ptr class? And why can't we use delete to remove it?

+5
source share
2 answers

If you had a function with a raw pointer

void f(T *t); // non-owning pointer 

And you had a smart pointer to the T object, you can pass it to this function 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 that use raw pointers are common and still useful. I suggest you watch this part of the CppCon 2014 Herb Sutter talk, and possibly the parts around it.

You should not try to delete this pointer, the smart pointer classes assume that you will not do anything, and still free the managed object in your own destructors when the time comes (in the end, how would he know that you deleted it?).

The task of the smart pointer is to manage the object and delete it at the right time, if you want to manually control the lifetime of the object (usually not recommended), and then use the raw pointer.

If you want to take responsibility for unique_ptr , you can do this by calling release() .

+11
source

Usually, you should use get() when you need to pass a raw pointer to an API that accepts such a pointer.

The shared_ptr class controls the ownership of the pointer, so it automatically deletes its memory when the smart pointer expires. If you try to delete the memory yourself, then when shared_ptr tries to free you, you will end the undefined behavior.

+4
source

All Articles