Search code examples
c++c++11shared-ptrweak-ptrmake-shared

In what sense does a weak_ptr 'own' a shared_ptr?


I was trying to write a caption for this question for like 10 minutes and as you will see I eventually failed. [Editor's note: I think I have fixed that.]

I was reading Herb Sutter's blog and the topic is using std::make_shared and its cons and pros. Please see the photo attached:

enter image description here

This is a small part of a very very interesting article which I highly recommend people read. My question is regarding this sentence:

A “weak reference” count to track the number of weak_ptrs currently observing the object. The shared housekeeping control block is destroyed and deallocated (and the shared object is deallocated if it was not already) when the last weak reference goes away.**

I don't really understand this statement. Initially when we create a std::shared_ptr by make_shared e.g. auto sp1 = make_shared<widget>();, there are no weak ptrs currently observing the sp1, so it will be deleted when the shared_ptr goes out of scope in the usual way.

So how does adding a weak reference change this behaviour? Can anyone explain this to me please?


Solution

  • The control block keeps track of all the weak_ptr references as well as the shared_ptr references. After all, the weak_ptr needs to look somewhere to see if the object is still valid.

    Hence, the control block cannot be de-allocated until all shared_ptrs and all weak_ptrs have been destroyed. If you use make_shared the control block and the object are allocated together, which is mostly an optimization, except if the object is outlived by any weak_ptrs.