[英]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. 我想使用像std库的shared_ptr这样的智能指针,但是可以在不删除那些指针的情况下为共享该对象的每个shared_ptr删除该对象。
For example if i use std::shared_ptr 例如,如果我使用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. std::shared_ptr
附带了std::weak_ptr
,该指针可以指向由一组std::shared_ptr
托管的对象,并检查其是否仍处于活动状态,但不会延长该对象的寿命。
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. 您只需要将原始std::shared_ptr
保留在您的对象中,然后将std::weak_ptr
借给该对象的其他用户即可。 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). 当必须销毁对象时,请重置std::shared_ptr
,然后所有剩余的std::weak_ptr
都可以知道(当用户尝试锁定它们时,它们将返回null std::shared_ptr
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.