A shared_ptr represents shared ownership semantics; a perticular shared_ptr can't decide that it will unilaterally destroy the shared object.
To do something like this, have one owing shared_ptr to the object along with other weak_ptrs (Weak pointers implement temporary shared ownership semantics.)
No.... there isn't a way to do exactly what you're asking. Aside from being completely contrary to what shared_ptr is for (shared ownership), it would be very dangerous if outside code just had its pointers magically disappear on it.
The whole idea of shared ownership is that everyone who has a shared_ptr owns it. Therefore the object will not be deleted until all owners are done with it.
What you are looking for is not shared ownership, but rather.. you want one part of the code to own the object, and all others to simply have access to it.
For this... you can use shared_ptr + weak_ptr
So yes, this can be accomplished, but through a design change.
- Give the owner(s) a shared_ptr to the object.
- Give all other areas of code (non-owners) a weak_ptr built from that shared_ptr.
- When the owner is done with the object, just let the shared_ptr die as normal.
- All existing weak_ptrs will null themselves. Or rather, they will fail when you try to obtain a shared_ptr to the object.