在基类中调用shared_from_this()时,bad_weak_ptr
我有一个 SuperParent
类、一个 Parent
类(派生自 SuperParent
),并且都包含一个 shared_ptr
到 < code>Child 类(其中包含指向 SuperParent
的 weak_ptr
)。不幸的是,我在尝试设置 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;
}
I have a SuperParent
class, a Parent
class (derived from SuperParent
) and both contain a shared_ptr
to a Child
class (which contains a weak_ptr
to a SuperParent
). Unfortunately, I'm getting a bad_weak_ptr
exception when trying to set the Child
's pointer. The code is the following:
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为你的Parent类继承了enable_shared_from_this两次。
相反,您应该通过 SuperParent 继承它一次。如果你希望能够获得shared_ptr<父>在 Parent 类中,您还可以从以下辅助类继承它:
然后,
This is because your Parent class inherits enable_shared_from_this twice.
Instead, you should inherit it once - through the SuperParent. And if you want to be able to get shared_ptr< Parent > within Parent class, you can inherit also it from the following helper class:
Then,