2012-02-21 4 views
4

IはSuperParentクラス、(SuperParent由来)Parentクラスがあり、両方とも(SuperParentからweak_ptrを含有する)Childクラスにshared_ptrを含みます。残念ながら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を通して1回継承する必要があります。そして、あなたは親クラス内の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> 
関連する問題