Are there any disadvantages using make_shared to create shared_ptr

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

Boost documentation claims

Requests from users were repeated for the factory function, which creates an object of a certain type and returns shared_ptr to it. In addition to convenience and style, such a function is also a safe exception and much faster, because it can use a single distribution for both the object and the corresponding block control, eliminating a significant part of the shared_ptr construction overhead. This eliminates one of the complaints about the high efficiency of shared_ptr.

+51
c ++ boost shared-ptr
Jan 27
source share
5 answers

I know at least two.

  • You must control the distribution. Not very big, but some old api like to return pointers that you should remove.
  • No custom debiter. I do not know why this is not supported, but it is not. That means your general pointers should use a vanilla detonator.

Pretty weak spots. so always try to use make_shared.

+26
Jan 27 '10 at 14:40
source share

In addition to the points provided by @deft_code, even weaker:

  • If you use weak_ptr , which live after all shared_ptr to this object have died, then the memory of this object will be in memory together with the control unit until the last weak_ptr disappears. In other words, the object is destroyed, but not freed until the last weak_ptr is destroyed.
+37
Jan 27
source share

From http://www.codesynthesis.com/~boris/blog/2010/05/24/smart-pointers-in-boost-tr1-cxx-x0/

Another drawback of make_shared () implementation is the increase in the size of the object code. Thanks to how this optimization is implemented, an additional virtual table will be created, as well as a set of virtual functions for each type of object that you use with make_shared ().

+14
May 10 '11 at 21:43
source share

In addition, make_shared not compatible with the factory pattern . This is because calling make_shared inside your factory function calls the library code, which in turn calls new , which it does not have access to , since it cannot call the private constructor of class (s) (the constructor must be private, if you follow the factory pattern correctly).

+8
Mar 04 '13 at 13:50
source share

When using sharing, you cannot specify how the allocation and release of the held object will be performed.

If necessary, use std::allocate_shared<T> instead:

 std::vector<std::shared_ptr<std::string>> avec; std::allocator<std::string> aAllocator; avec.push_back(std::allocate_shared<std::string>(aAllocator,"hi there!")); 

Please note that the vector should not be informed about the dispenser!

To create a custom dispenser, see here https://stackoverflow.com/a/166778/

+7
Nov 04
source share



All Articles