Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the uses of get() member from the shared_ptr class?

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?

like image 955
Cpp Programmer Avatar asked Apr 27 '15 17:04

Cpp Programmer


People also ask

What does the get () function of the unique_ptr class do?

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.

What is the use of shared_ptr?

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.

What is shared_ptr?

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.

How do I find the value of a shared pointer?

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.


2 Answers

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().

like image 103
Ryan Haining Avatar answered Oct 23 '22 22:10

Ryan Haining


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.

like image 4
Mark B Avatar answered Oct 23 '22 22:10

Mark B