简体   繁体   中英

shared_ptr object global deletion

I wanted to use a smart pointer like shared_ptr of std library but where it would be possible to delete the object for every shared_ptr that share it without deleting those pointers.

For example if i use std::shared_ptr

shared_ptr<A> p1 = make_share<A>();
shared_ptr<A> p2 = shared_ptr<A>(p1);
p1.reset();
// now p2 still contain the object of type A
// instead of nullptr

Is there a way to do that or does some alternatives exist? Am i doing it wrong?

Absolutely. std::shared_ptr comes with std::weak_ptr , a pointer that can point to an object managed by a set of std::shared_ptr s and check whether it is still alive, but does not extends the object's lifetime.

You just have to keep the original std::shared_ptr to your object, and lend std::weak_ptr s to other users of that object. When the object must be destroyed, reset the std::shared_ptr , and all remaining std::weak_ptr s will be able to tell (they'll return null std::shared_ptr s when the users try to lock them).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM