c++ - 在基类中调用 shared_from_this() 时的 bad_weak_ptr

标签 c++ boost shared-ptr weak-references

我有一个 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;
}

最佳答案

这是因为你的Parent类继承了两次enable_shared_from_this。 相反,您应该继承它一次——通过 SuperParent。如果你想在 Parent 类中获得 shared_ptr< Parent >,你也可以从以下帮助类继承它:

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>

关于c++ - 在基类中调用 shared_from_this() 时的 bad_weak_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374610/

相关文章:

c++ - 高效解释串行数据

c++在fork之后初始化全局对象

c++ - 如何重新绑定(bind) Boost.TypeErasure any<...> 对象

c++ - gmock SetArgReferee : Set a non-copyable non-moveable object

c++ - 你可以使用 boost::shared_ptr 作为 map 的键吗?

c++ - shared_ptr 与 CComPtr

c++ - Makefile 链接问题

C++虚方法重载/覆盖编译器错误

c++ - Visual Studio 中的这些 .pch 和 .ncb 文件是什么?

c++ - 了解当传递给函数时,shared_ptr 引用计数何时增加