Reputation: 6546
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:
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?
Upvotes: 2
Views: 311
Reputation: 8268
Simply put, a shared_ptr
owns the managed object and the meta information (the control block) and a weak_ptr
owns only the meta information.
Ownership means that:
The reference counting part is an implementation detail. (You could have a linked list if you love very inefficient implementations with a mutex instead of relatively efficient atomic counters.)
Upvotes: 2
Reputation: 932
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_ptr
s and all weak_ptr
s 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_ptr
s.
Upvotes: 5