2012-02-21 62 views
4

当我有一个SuperParent类,一类Parent(来自SuperParent衍生)和既含有shared_ptrChild类(其含有一个weak_ptrSuperParent)。不幸的是,当试图设置Child的指针时,我得到了一个bad_weak_ptr异常。代码如下:bad_weak_ptr调用shared_from_this()中的基类

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

回答

5

这是因为您的父类继承两次enable_shared_from_this。 相反,你应该继承它 - 通过SuperParent。如果你希望能够父类中获得的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>