【问题标题】:bad_weak_ptr when calling shared_from_this() in base class在基类中调用 shared_from_this() 时的 bad_weak_ptr
【发布时间】: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


    【解决方案1】:

    这是因为您的 Parent 类继承了 enable_shared_from_this 两次。 相反,您应该继承它一次 - 通过 SuperParent。如果您希望能够在 Parent 类中获取 shared_ptr,您也可以从以下帮助类继承它:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多