bad_weak_ptr when calling shared_from_this() in base class

可紊 提交于 2019-12-05 10:47:04

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

Then,

class Parent : public SuperParent, public enable_shared_from_This<Parent>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!