I understand about what methods are available and what they are. Please, describe private section of weak_ptr class or give example of some custom weak_ptr code. I can't understand by std::weak_ptr implementation.
An unintrusive shared pointer implementation usually contains a pointer to some dynamically-allocated "state", which counts how many references there are to the original object.
When a shared pointer is copied, the copy gets the same pointer to the same "state", and the count inside the "state" is incremented to indicate that there are now two shared pointers sharing the resource.
When a shared pointer is destroyed, it decrements the counter to indicate that there is now one fewer pointer sharing the resource. If this results in the counter reading zero, the resource is destroyed.
A weak pointer also has a pointer to this "state", but it doesn't increment or decrement the counter. When asked, it will construct a shared pointer using the same state, but only if the count is not zero. If the count is zero, the last shared pointer already destroyed the resource, and we can't get access to it any more.
What's interesting is that you also need logic like this to control the lifetime of the "state" object. :) (I'd imagine that's implemented using a second counter, which both shared_ptr
and weak_ptr
do increment, but don't quote me on that.)
(your data) (ref. counters)
║ ║
[resource] [state]
┆ │ │ │ │ │
┆ │ └─[shared_ptr]───┘ │ │
┆ └───[shared_ptr]─────┘ │
└┄┄┄┄┄┄┄[weak_ptr]────────┘
Of course, what the private section of any particular std::weak_ptr
implementation exactly looks like is up to the person who wrote it.
Incidentally, the diagram kind of shows why you shouldn't construct a shared_ptr
from a raw pointer, if you suspect that the resource it points to may already be managed by shared_ptr
(s) elsewhere: you'd get a second, unrelated "state" object, your counters will be wrong, and your resource may be destroyed prematurely (and will definitely be destroyed twice, if such a notion exists), causing mayhem.