我正在开发一个应用程序,它严重依赖于
下面的图表描述了我的意思(黑色箭头表示
我已经测试过了,它似乎可以正常工作(没有任何内存泄漏的报告),但是我的问题是:这是否安全?如果不安全,为什么?
shared_ptr
,目前一切看起来都很好 - 我已经做了功课,对使用shared_ptr
的一些陷阱有了相当清晰的认识。
shared_ptr
最为人所知的问题之一是循环依赖 - 这些问题可以通过存储不影响上游对象生命周期的weak_ptr
来解决。然而,我在理解需要通过weak_ptr
存储指向外部对象的指针的时候遇到了困难 - 我不确定这是否被禁止、不鼓励还是安全的。下面的图表描述了我的意思(黑色箭头表示
shared_ptr
; 虚线表示weak_ptr
):
alt text http://img694.imageshack.us/img694/6628/sharedweakptr.png
- 一个父类包含指向两个子类的
shared_ptr
,两个子类使用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();
}
我已经测试过了,它似乎可以正常工作(没有任何内存泄漏的报告),但是我的问题是:这是否安全?如果不安全,为什么?