bru*_*ery 5 c++ boost weak-references shared-ptr
我有一个SuperParent类,一个Parent类(派生自SuperParent),并且都包含shared_ptr一个Child类(包含a weak_ptr到a SuperParent).不幸的是,我bad_weak_ptr在尝试设置Child指针时遇到异常.代码如下:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是因为您的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());
}
};
Run Code Online (Sandbox Code Playgroud)
然后,
class Parent : public SuperParent, public enable_shared_from_This<Parent>
Run Code Online (Sandbox Code Playgroud)