2013-04-18 59 views
15

BIはenable_shared_from_thisを私のコードで使用していますが、その使用法が正しいかどうかはわかりません。これはコードです:複数の継承を持つenable_shared_from_thisの使用

class A: public std::enable_shared_from_this<A> 
{ 
public: 
    void foo1() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class B:public std::enable_shared_from_this<B> 
{ 
public: 
    void foo2() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class C:public std::enable_shared_from_this<C> 
{ 
public: 
    void foo3() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class D: public A, public B, public C 
{ 
public: 
    void foo() 
    { 
     auto ptr = A::shared_from_this(); 
    } 
}; 

は、彼らが常にDのshared_ptrを通じて呼び出されていると仮定して、正しいmake_shared_from_this()のこれらの使用法はありますか?

+0

私は 'foo2'または' foo3'がコンパイルう...意味をなさない – aschepler

+0

うんは、唯一のクラスAは、

+0

私はあなたがenable_shared_from_this何を見てみるべきだと思いますそうです。この[質問](http://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this)への答えを参照してください –

答えて

21

本当に間違っています。簡単な継承をしている場合は、基本クラスのenable_shared_from thisから継承し、派生クラスを無料で入手してください。 hereを説明し、またhere(もちろん、あなたが結果をダウンキャストする必要があります)

あなたは多重継承(それはそうのような)を持っている場合は、あなたがトリックを使用する必要があります。

/* Trick to allow multiple inheritance of objects 
* inheriting shared_from_this. 
* cf. https://stackoverflow.com/a/12793989/587407 
*/ 

/* First a common base class 
* of course, one should always virtually inherit from it. 
*/ 
class MultipleInheritableEnableSharedFromThis: public std::enable_shared_from_this<MultipleInheritableEnableSharedFromThis> 
{ 
public: 
    virtual ~MultipleInheritableEnableSharedFromThis() 
    {} 
}; 

template <class T> 
class inheritable_enable_shared_from_this : virtual public MultipleInheritableEnableSharedFromThis 
{ 
public: 
    std::shared_ptr<T> shared_from_this() { 
    return std::dynamic_pointer_cast<T>(MultipleInheritableEnableSharedFromThis::shared_from_this()); 
    } 
    /* Utility method to easily downcast. 
    * Useful when a child doesn't inherit directly from enable_shared_from_this 
    * but wants to use the feature. 
    */ 
    template <class Down> 
    std::shared_ptr<Down> downcasted_shared_from_this() { 
    return std::dynamic_pointer_cast<Down>(MultipleInheritableEnableSharedFromThis::shared_from_this()); 
    } 
}; 

次に、あなたのコードは次のようになります。

class A: public inheritable_enable_shared_from_this<A> 
{ 
public: 
    void foo1() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class B: public inheritable_enable_shared_from_this<B> 
{ 
public: 
    void foo2() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class C: public inheritable_enable_shared_from_this<C> 
{ 
public: 
    void foo3() 
    { 
     auto ptr = shared_from_this(); 
    } 
}; 

class D: public A, public B, public C 
{ 
public: 
    void foo() 
    { 
     auto ptr = A::downcasted_shared_from_this<D>(); 
    } 
}; 
+0

注:継承されたクラスは、継承されたenable_shared_from_thisがpublicの場合にのみ使用できます。つまり、 'class BaseClass:public enable_shared_from_this 'です。 – Andrew

関連する問題