【发布时间】:2012-02-21 08:55:20
【问题描述】:
我有一个SuperParent 类,一个Parent 类(派生自SuperParent),它们都包含一个shared_ptr 到一个Child 类(其中包含一个weak_ptr 到一个SuperParent)。不幸的是,我在尝试设置Child 的指针时遇到bad_weak_ptr 异常。代码如下:
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using namespace boost;
class SuperParent;
class Child {
public:
void SetParent(shared_ptr<SuperParent> parent)
{
parent_ = parent;
}
private:
weak_ptr<SuperParent> parent_;
};
class SuperParent : public enable_shared_from_this<SuperParent> {
protected:
void InformChild(shared_ptr<Child> grandson)
{
grandson->SetParent(shared_from_this());
grandson_ = grandson;
}
private:
shared_ptr<Child> grandson_;
};
class Parent : public SuperParent, public enable_shared_from_this<Parent> {
public:
void Init()
{
child_ = make_shared<Child>();
InformChild(child_);
}
private:
shared_ptr<Child> child_;
};
int main()
{
shared_ptr<Parent> parent = make_shared<Parent>();
parent->Init();
return 0;
}
【问题讨论】:
标签: c++ boost shared-ptr weak-references