次の方法で共有


enable_shared_from_this クラス

shared_ptr の生成を支援します。

構文

class enable_shared_from_this {
public:
    shared_ptr<Ty>
        shared_from_this();
    shared_ptr<const Ty> shared_from_this() const;
    weak_ptr<T> weak_from_this() noexcept;
    weak_ptr<T const> weak_from_this() const noexcept;
protected:
    enable_shared_from_this();
    enable_shared_from_this(const enable_shared_from_this&);
    enable_shared_from_this& operator=(const enable_shared_from_this&);
    ~enable_shared_from_this();
};

パラメーター

Ty
共有ポインターによって制御される型。

解説

enable_shared_from_this の派生オブジェクトは、メンバー関数の shared_from_this メソッドを使って、既存の shared_ptr 所有者と所有権を共有するインスタンスの shared_ptr 所有者を作成できます。 それ以外の場合は、this を使って作成した新しい shared_ptr は、既存の shared_ptr 所有者とは区別され、無効な参照になるか、またはオブジェクトが複数回削除される可能性があります。

コンストラクター、デストラクター、および代入演算子は、偶発的な誤用を防ぐために保護されています。 テンプレート引数型 Ty は、派生クラスの型である必要があります。

使用方法の例については、「enable_shared_from_this::shared_from_this」をご覧ください。

shared_from_this

インスタンスの所有権を既存の shared_ptr 所有者と共有する shared_ptr を生成します。

shared_ptr<T> shared_from_this();
shared_ptr<const T> shared_from_this() const;

解説

基底クラス enable_shared_from_this からオブジェクトを派生すると、shared_from_this テンプレート メンバー関数は、このインスタンスの所有権を既存の shared_ptr 所有者と共有する shared_ptr クラスのオブジェクトを返します。 それ以外の場合は、this から作成した新しい shared_ptr は、既存の shared_ptr 所有者とは区別され、無効な参照になるか、またはオブジェクトが複数回削除される可能性があります。 shared_ptr オブジェクトによってまだ所有されていないインスタンスで shared_from_this を呼び出した場合の動作は未定義です。

// std_memory_shared_from_this.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

using namespace std;

struct base : public std::enable_shared_from_this<base>
{
    int val;
    shared_ptr<base> share_more()
    {
        return shared_from_this();
    }
};

int main()
{
    auto sp1 = make_shared<base>();
    auto sp2 = sp1->share_more();

    sp1->val = 3;
    cout << "sp2->val == " << sp2->val << endl;
    return 0;
}
sp2->val == 3

weak_from_this

weak_ptr<T> weak_from_this() noexcept;
weak_ptr<T const> weak_from_this() const noexcept;