2015-12-03 20 views
10

の仕組み私はちょうどstd::enable_shared_from_this::shared_from_thisは、既存のポインタで所有権を共有する共有ピンターを返す方法を理解することはできません。言い換えれば、あなたはthisの操作を行います。getFooを呼び出すときのstd :: enable_shared_from_this :: shared_from_thisが

std::shared_ptr<Foo> getFoo() { return shared_from_this(); } 

だから、どのように正確にそれはとの所有権を共有する他のshared_ptrであり、同じthis所有している別のshared_ptrを作成しないものを手に入れるん。

shared_ptrを作成して同じrefカウントを増やし、個別のshared_ptrを初期化しないオブジェクトから、どのようにshared_ptrを作成するかを理解する必要があります。

+2

がhttp://en.cppreference.com/w/cpp/memory/enable_shared_from_this私は一般的な実装を説明する注意事項を見てきました – StoryTeller

+0

ノートを見てください。それ以前は、ソースコードも見てきました。しかし、最初にshared_ptrがクラス外に作成されたときに、この 'weak_ptr'がどのように初期化されているのか理解できませんでした。あるクラスは、 'shared_ptr'にポインタをカプセル化したことを知ることができません。 – Narek

+2

'std :: shared_ptr'のソースも見てください。このノートでは、 'std :: enable_shared_from_this'の存在を基底クラスとして検出するコードがあることを明確に示しています。 – StoryTeller

答えて

16

enable_shared_from_this<T>weak_ptr<T>データメンバを持っています。 shared_ptr<T>コンストラクタは、enable_shared_from_this<T>から派生したものかどうかを検出することができます。もしそうであれば、shared_ptr<T>コンストラクタはenable_shared_from_this<T>weak_ptrデータメンバに(shared_ptr<T>ある)*thisを割り当てます。 shared_from_this()weak_ptr<T>からshared_ptr<T>を作成できます。可能な実装の

例:

template<class D> 
class enable_shared_from_this { 
protected: 
    constexpr enable_shared_from_this() { } 
    enable_shared_from_this(enable_shared_from_this const&) { } 
    enable_shared_from_this& operator=(enable_shared_from_this const&) { 
     return *this; 
    } 

public: 
    shared_ptr<T> shared_from_this() { return self_.lock(); } 
    shared_ptr<T const> shared_from_this() const { return self_.lock(); } 

private: 
    weak_ptr<D> self_; 

    friend shared_ptr<D>; 
}; 

template<typename T> 
shared_ptr<T>::shared_ptr(T* ptr) { 
    // ... 
    // Code that creates control block goes here. 
    // ... 

    // NOTE: This if check is pseudo-code. Won't compile. There's a few 
    // issues not being taken in to account that would make this example 
    // rather noisy. 
    if (is_base_of<enable_shared_from_this<T>, T>::value) { 
     enable_shared_from_this<T>& base = *ptr; 
     base.self_ = *this; 
    } 
} 
+0

'shared_ptr'が' enable_shared_from_this'の 'weak_ptr'メンバーにアクセスする方法(私はそれがプライベートだと思います)。 – Narek

+3

@ナレクそれはおそらく '友人 'です。 C++ 17では – Simple

+0

、あなたのようにコンパイル時の枝を使って、(現在*擬似コード*である) 'if'チェックをコンパイルすることができます:' constexprの場合は(...){...} ' – Nawaz

関連する問題