shared pointer dropping?

Hi,
Is their a way to completely drop a shared_ptr. Then it will delete the memory and NULL all pointers linking to it?

Thanks,
Dan
No.

If you want that functionality, then let all std::shared_ptr instances fall out of scope. Other code that only needs access if the pointed-to object still exists should use std::weak_ptr.
http://www.cplusplus.com/reference/memory/weak_ptr/
http://en.cppreference.com/w/cpp/memory/weak_ptr
Last edited on
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.)
Yes and no:


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.


EDIT:

Ninja'd twice!
Last edited on
Haha thats brilliant!

Thanks guys for your help
Topic archived. No new replies allowed.