Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any downsides with using make_shared to create a shared_ptr

Are there any downsides with using make_shared<T>() instead of using shared_ptr<T>(new T).

Boost documentation states

There have been repeated requests from users for a factory function that creates an object of a given type and returns a shared_ptr to it. Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead. This eliminates one of the major efficiency complaints about shared_ptr.

like image 775
Tobias Furuholm Avatar asked Jan 27 '10 14:01

Tobias Furuholm


People also ask

Why should I use Make_shared?

As well as this efficiency, using make_shared means that you don't need to deal with new and raw pointers at all, giving better exception safety - there is no possibility of throwing an exception after allocating the object but before assigning it to the smart pointer.

Why is Make_shared more efficient?

One reason is because make_shared allocates the reference count together with the object to be managed in the same block of memory. OK, I got the point. This is of course more efficient than two separate allocation operations.

What happens if Make_shared fails?

So, if you throw exception from your class' constructor, then std::make_shared will throw it too. Besides exceptions thrown from constructor, std::make_shared could throw std::bad_alloc exception on its own. Therefore, you don't need to check if the result of std::make_shared is nullptr .

When should I use shared_ptr?

Use shared_ptr if you want to share ownership of a resource. Many shared_ptr can point to a single resource. shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed.


1 Answers

In addition to the points presented by @deft_code, an even weaker one:

  • If you use weak_ptrs that live after all the shared_ptrs to a given object have died, then this object's memory will live in memory along with the control block until the last weak_ptr dies. In other words the object is destroyed but not deallocated until the last weak_ptr is destroyed.
like image 116
sbk Avatar answered Oct 11 '22 02:10

sbk