I understand how to use weak_ptr and shared_ptr. I understand how shared_ptr works, by counting the number of references in its object. How does weak_ptr work? I tried reading through the boost source code, and I’m not familiar enough with boost to understand all the things it uses.
Thanks.
shared_ptruses an extra “counter” object (aka. “shared count” or “control block”) to store the reference count.(BTW: that “counter” object also stores the deleter.)
Every
shared_ptrandweak_ptrcontains a pointer to the actual pointee, and a second pointer to the “counter” object.To implement
weak_ptr, the “counter” object stores two different counters:shared_ptrinstances pointing to the object.weak_ptrinstances pointing to the object, plus one if the “use count” is still > 0.The pointee is deleted when the “use count” reaches zero.
The “counter” helper object is deleted when the “weak count” reaches zero (which means the “use count” must also be zero, see above).
When you try to obtain a
shared_ptrfrom aweak_ptr, the library atomically checks the “use count”, and if it’s > 0 increments it. If that succeeds you get yourshared_ptr. If the “use count” was already zero you get an emptyshared_ptrinstance instead.EDIT: Now, why do they add one to the weak count instead of just releasing the “counter” object when both counts drop to zero? Good question.
The alternative would be to delete the “counter” object when both the “use count” and the “weak count” drop to zero. Here’s the first reason: Checking two (pointer sized) counters atomically is not possible on every platform, and even where it is, it’s more complicated than checking just one counter.
Another reason is that the deleter must stay valid until it has finished executing. Since the deleter is stored in the “counter” object, that means the “counter” object must stay valid. Consider what could happen if there is one
shared_ptrand oneweak_ptrto some object, and they are reset at the same time in concurrent threads. Let’s say theshared_ptrcomes first. It decreases the “use count” to zero, and begins executing the deleter. Now theweak_ptrdecreases the “weak count” to zero, and finds the “use count” is zero as well. So it deletes the “counter” object, and with it the deleter. While the deleter is still running.Of course there would be different ways to assure that the “counter” object stays alive, but I think increasing the “weak count” by one is a very elegant and intuitive solution. The “weak count” becomes the reference count for the “counter” object. And since
shared_ptrs reference the counter object too, they too have to increment the “weak count”.A probably even more intuitive solution would be to increment the “weak count” for every single
shared_ptr, since every singleshared_ptrhold’s a reference to the “counter” object.Adding one for all
shared_ptrinstances is just an optimization (saves one atomic increment/decrement when copying/assigningshared_ptrinstances).