本文介绍了bad_weak_ptr当调用基类中的shared_from_this()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SuperParent 类,类(派生自 SuperParent )都包含 shared_ptr Child 类(其中包含 weak_ptr SuperParent )。不幸的是,当尝试设置 Child 的指针时,我会得到 bad_weak_ptr 异常。代码如下:

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;
}


推荐答案

继承两次enable_shared_from_this。
相反,你应该继承它一次 - 通过SuperParent。如果你想能够得到shared_ptr< Parent>在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:

template<class Derived> 
class enable_shared_from_This
{
public:
typedef boost::shared_ptr<Derived> Ptr;

Ptr shared_from_This()
{
    return boost::static_pointer_cast<Derived>(static_cast<Derived *>(this)->shared_from_this());
}
Ptr shared_from_This() const
{
    return boost::static_pointer_cast<Derived>(static_cast<Derived *>(this)->shared_from_this());
}
};

然后,

class Parent : public SuperParent, public enable_shared_from_This<Parent>

这篇关于bad_weak_ptr当调用基类中的shared_from_this()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 09:35