views:

401

answers:

2

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.

+2  A: 

I know of at least two.

  • You must be in control of the allocation. Not a big one really, but some older api's like to return pointers that you must delete.
  • No custom deleter. I don't know why this isn't supported, but it isn't. That means your shared pointers have to use a vanilla deleter.

Pretty weak points. so try to always use make_shared.

caspin
There's no custom deleter because only `make_shared` itself knows how to delete the object.
Mike Seymour
+2  A: 

In addition to the points presented by Caspin, even weaker one:

  • If you use weak_ptrs that live after all the shared_ptrs to a given object have died, then this object will live in memory along with the control block until the last weak_ptr dies.
sbk
That's also the case if you don't use `make_shared`. The only difference is that the control block will be in a separately allocated lump of memory.
Mike Seymour
@Mike: surely not - normally, if there are no shared_ptrs to the object, only weak_ptrs, then the object is deleted immediately. I don't know off-hand whether the control block remains, I'll take your word for it. With make_shared, the control block and the object co-habit a single allocation, so if the memory for one of them remains then both do (although I'd guess the object is destructed, just the memory not freed?).
Steve Jessop
Er, yeah. Sorry. I must have had my other brain in when I wrote that.
Mike Seymour