Search code examples
c++c++11stlshared-ptrweak-ptr

std::shared_ptr, std::weak_ptr and control block


I've been reading about std::make_shared function lately. As far as I understand from Effective Modern C++ book, the make function should be preferred unless:

  1. Custom memory management is in place.
  2. There are memory concerns such as std::weak_ptr may outlive its std::shared_ptr, dealing with large objects, custom deleter, etc.

So, I understand std::make_shared allocates an object on the heap and its control block with just one call. Hence, the problem is std::shared_ptr's object may not be deleted until control block has to be released. Correct me if I am wrong, but this is when the last std::weak_ptr is released. Thus, std::make_shared may not be suitable if there is an alive std::weak_ptr which points to it.

But is this still a problem for most objects? Do we need to care when control block is released for non-large objects? Arguably, memory isn't that hard to get nowadays, so is this a concern for just large objects and low memory systems?

The point of my concern is: if I design a class which uses std::make_shared, and std::weak_ptr is used in the future, I have to go back and replace the make function with a regular std::shared_ptr<Class>(new Class()).


Solution

  • This is a tiny edge issue that gets blown way out of proportion. The only case where this is a problem is if the object is large (relative to available memory), the size is in the base size of the object (not memory that the destructor (of the object or of any of its members) can free), and a weak pointer is likely to significantly outlive the object. This is a rare combination of cases and is almost never significant.