2012-02-21 88 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>