I need single ownership for an object because I need to be able to destroy it on demand (this makes sense sometimes; in this case the object represents a logged-in session that, for security reasons, the user wants to close). Let's call this object session. Other client objects keep references to session, but, of course, it may be dead when the clients access the reference.
What I'm after is a 'safe reference' that is notified when the original object is destroyed and reports this gracefully (exception, boolean) to the client, instead of a segfault.
Does anything like this exist? Preferable using what's available in standard C++/Boost. Preferably C++03. shared_ptr with weak_ptr is almost what I'm after, if only the shared_ptrs didn't extend the lifetime of session. I need to guarantee that session has been destroyed and a stray shared_ptr would prevent that.
There is a fundamental problem with the design you are requesting.
Suppose you have a session and a user of the session. The user checks that the session is valid, then uses it. Meanwhile the session becomes invalid, between checking and use. weak_ptr deals with this by allowing the user to upgrade to shared_ptr, then check and use that. Your design precludes that.
If you are willing to ignore that problem, I have a solution.
The object keeps a shared_ptr<void> (allocated as a char) as a member. It exposes weak_ptr<void> which can be used to track its lifetime, but not determine it. The object itself is unique_ptr stored, and the users keep a raw pointer and lifetime tracker pair.
This does not provide for immediate update of lifetime termination: for that use the callback pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With