Is there a smart pointer that is automatically nulled when its target is destroyed in C++

前提是你 提交于 2019-12-23 12:37:19

问题


I've found QPointer. Are there any others?


回答1:


Boost - the weak_ptr has some nice features that make it safe to use, if you are also using shared_ptr. You keep a weak_ptr reference to an instance that is managed by shared_ptr lifetime. When you need to use the underlying instance, convert it to a shared_ptr instance using the constructor of the shared_ptr class, or the lock method. The operation will fail if the underlying instance was deleted. The use is thread safe in the same fashion as the shared_ptr class:

shared_ptr<int> p(new int(5));
weak_ptr<int> q(p);

// some time later

if(shared_ptr<int> r = q.lock())
{
    // use *r
}



回答2:


"boost::weak_ptr" works really well with "boost::shared_ptr" (also available in tr1)



来源:https://stackoverflow.com/questions/909437/is-there-a-smart-pointer-that-is-automatically-nulled-when-its-target-is-destroy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!