我目前正在组装一个严重依赖 shared_ptr
的应用程序,到目前为止一切看起来都很好 - 我已经完成了我的 homework 并且非常清楚使用 shared_ptr
的一些陷阱
shared_ptr
最常见的问题之一是循环依赖 - 这些问题可以通过存储 weak_ptr
来解决,这些 weak_ptr
不会影响上链对象的生命周期.但是,我很难理解需要通过 weak_ptr
存储指向外部对象的指针的时间 - 我不确定它是否被禁止、不鼓励,或者是否这是安全的。
下图描述了我的意思(黑色箭头表示shared_ptr
;虚线表示weak_ptr
):
alt text http://img694.imageshack.us/img694/6628/sharedweakptr.png
- 父级包含两个子级的
shared_ptr
,这两个子级都使用weak_ptr
指向父级。 - 在第一个 child 的构造函数中,我通过父
weak_ptr
检索指向第二个 child 的指针并将其存储在本地。<
代码如下所示:
#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();
}
我已经对此进行了测试,它似乎工作正常(我没有收到任何内存泄漏报告),但我的问题是:这安全吗?如果不是,为什么不呢?
最佳答案
子构造函数在您调用它的方式中似乎是安全的。但是一般来说它并不安全。
问题是由于在子构造函数中传入了一个 weak_ptr 作为参数。这意味着您需要担心弱指针是否指向不再存在的对象。通过将此参数更改为 shared_ptr 并在存储时转换为 weak_ptr 我们知道该对象仍然存在。这是变化:
child(boost::shared_ptr<parent> p)
{
_parent = p;
_child2 = p->_child2; // This is this safe
}
关于c++ - 使用 shared_ptr 和 weak_ptr 时避免间接循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2139266/