Herb Sutter just published a new Guru of the Week in which he claims one should always use make_shared when created shared pointers.

This is very good advice (as one can expect from Herb) but I can’t resist the urge to nitpick.

As Herb states the advantage of using make_shared is that when you use plain new the shared_ptr object must allocate the reference counting block separately from the (existing) tracked object

On the other hand when using make_shared both the tracked object and the reference counting can be allocated together.

This has the following advantages:

One less memory allocation (and deallocation), this is both faster and takes up less memory (the allocator overhead for size tracking)

Increased data locality, the ref counts and the object are probably in the same memory page (perhaps even the same cache line)

However there could be rare cases in which the make_shared implementation has a drawback. Consider what happens if we use weak_ptr s to break cycles in our ownership graph and the object’s strong references expire while some weak references hold on. This means that the pointed at object must be destroyed but we still need the reference counts (specifically the weak reference count).

So in the case where we used plain-old new we get:

void releaseStrongRef ( ) { if ( - - data_ - > strongRefs_ = = 0 ) delete data_ - > value_ ; // destroy object and free its memory if ( data_ - > weakRefs_ = = 0 ) delete data_ ; } void releaseWeakRef ( ) { if ( - - data_ - > weakRefs_ = = 0 ) delete data_ ; }

While the make_shared implementation will have to hold on to the memory till the weak references are released:

void releaseStrongRef ( ) { if ( - - data_ - > strongRefs_ = = 0 ) data_ - > value_ - > ~ T ( ) ; // explicitly destroy object, memory isn't freed if ( data_ - > weakRefs_ = = 0 ) delete data_ ; } void releaseWeakRef ( ) { if ( - - data_ - > weakRefs_ = = 0 ) delete data_ ; }

So if you’re expecting to use weak_ptr s that will outlive your pointed to object and you need your memory back ASAP consider not using make_shared .