1
votes

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

1
Is this really an actual problem? Shared pointers should be rare enough as it is; have you measured any actual bottlenecks that motivate this question? - Kerrek SB
No, but what motivates my question is the possible need for redesign based on the above mentioned book's advice. It is said the make function may not be a good idea when there is still a std::weak_ptr. - bbalchev
"Largeness" here is measured by sizeof, so most types aren't large. The object is destroyed when the last living shared_ptr is destroyed; only the memory isn't released until the control block goes away. - T.C.
So, even though the object is destroyed, it still uses memory. Is that right? So, at what point do I need to care when the control block goes away (i.e. I shouldn't use std::make_shared)? - bbalchev
Smart pointers have nothing to do with the "Standard Template Library". - curiousguy

1 Answers

6
votes

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.