Ala*_*lan 7 c++ boost shared-ptr cyclic weak-ptr
我目前正在整理一个严重依赖的应用程序,shared_ptr到目前为止一切看起来都很好 - 我已经完成了我的功课,对使用shared_ptrs 的一些陷阱非常了解.
最常见的问题之一shared_ptr是循环依赖 - 这些问题可以通过存储weak_ptr不影响链上对象生命周期的问题来解决.然而,我正在努力解决需要通过以下方式存储指向外部对象的指针weak_ptr- 我不确定它是否被禁止,气馁或是否安全.
下图描述了我的意思(黑色箭头表示shared_ptr;虚线表示weak_ptr):
替代文字http://img694.imageshack.us/img694/6628/sharedweakptr.png
shared_ptr两个子节点,两个子节点都使用a指向父节点weak_ptr. weak_ptr指向第二个子节点的指针并将其存储在本地.代码如下所示:
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
class child;
class child2;
class parent;
class parent : public boost::enable_shared_from_this<parent>
{
public:
void createChildren()
{
_child2 = boost::make_shared<child2>(shared_from_this());
_child = boost::make_shared<child>(shared_from_this());
}
boost::shared_ptr<child> _child;
boost::shared_ptr<child2> _child2;
};
class child
{
public:
child(boost::weak_ptr<parent> p)
{
_parent = p;
_child2 = boost::shared_ptr<parent>(p)->_child2; // is this safe?
}
boost::weak_ptr<parent> _parent;
boost::shared_ptr<child2> _child2;
};
class child2
{
public:
child2(boost::weak_ptr<parent> p)
{
this->_parent = p;
}
boost::weak_ptr<parent> _parent;
};
int main()
{
boost::shared_ptr<parent> master(boost::make_shared<parent>());
master->createChildren();
}
Run Code Online (Sandbox Code Playgroud)
我已经测试了这个并且似乎工作正常(我没有得到任何内存泄漏的报告),但我的问题是:这样安全吗?如果没有,为什么不呢?
子构造函数看起来像你调用它一样安全.然而,它一般不安全.
问题是由于传递了一个weak_ptr作为子构造函数中的参数.这意味着您需要担心弱指针是否适用于不再存在的对象.通过将此参数更改为shared_ptrs并在存储时转换为weak_ptr,我们知道该对象仍然存在.这是改变:
child(boost::shared_ptr<parent> p)
{
_parent = p;
_child2 = p->_child2; // This is this safe
}
Run Code Online (Sandbox Code Playgroud)
如果 'p' 已经(以某种方式)被破坏,你会得到 bad_weak_ptr 异常。因此,child ctor 期望出现异常是安全的,否则就不安全。