名前空間
変種
操作

std::enable_shared_from_this

From cppreference.com
< cpp‎ | memory
 
 
メモリ管理ライブラリ
(説明用*)
未初期化メモリのアルゴリズム
(C++17)
(C++17)
(C++17)
制約付き未初期化
メモリアルゴリズム
Cライブラリ

アロケータ
メモリリソース
ガベージコレクションのサポート
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
未初期化ストレージ
(C++20まで*)
(C++20まで*)
明示的な生存期間管理
 
 
ヘッダ <memory> で定義
template< class T >
class enable_shared_from_this;
(C++11以降)

std::enable_shared_from_this を使用すると、現在 std::shared_ptr (名前は pt) によって管理されているオブジェクト t が、ptt の所有権を共有する追加の std::shared_ptr インスタンス (pt1pt2 など) を安全に生成できるようになります。

std::enable_shared_from_this<T> から公開継承すると、型 T にメンバー関数 shared_from_this が提供されます。型 T のオブジェクト tstd::shared_ptr<T> (名前は pt) によって管理されている場合、T::shared_from_this を呼び出すと、ptt の所有権を共有する新しい std::shared_ptr<T> が返されます。

目次

[編集] データメンバー

メンバ 説明
mutable std::weak_ptr<T> weak_this *this の最初の共有所有者のコントロールブロックを追跡するオブジェクト
(説明用のメンバオブジェクト*)

[編集] メンバー関数

enable_shared_from_this オブジェクトを構築します。
(protected メンバ関数)
enable_shared_from_this オブジェクトを破棄します。
(protected メンバ関数)
*this への参照を返します。
(protected メンバ関数)
*this の所有権を共有する std::shared_ptr を返します。
(public member function)
*this の所有権を共有する std::weak_ptr を返します。
(public member function)

[編集] 注釈

std::shared_ptr のコンストラクタは、曖昧でアクセス可能な (つまり、public 継承が必須) enable_shared_from_this 基底の存在を検出し、生存している std::shared_ptr によってまだ所有されていない場合、新しく作成された std::shared_ptrweak_this に割り当てます。すでに別の std::shared_ptr によって管理されているオブジェクトに対して std::shared_ptr を構築しても weak_this は参照されず、未定義の動作につながります。

shared_from_this は、以前に共有されたオブジェクト、つまり std::shared_ptr<T> によって管理されているオブジェクトに対してのみ呼び出すことができます。それ以外の場合、std::bad_weak_ptr がスローされます (デフォルト構築された weak_this からの std::shared_ptr コンストラクタによって)。

enable_shared_from_this は、std::shared_ptr<T>(this) のような式に対する安全な代替手段を提供します。このような式は、互いを認識しない複数の所有者によって this が複数回破棄される可能性が高いです (以下の例を参照)。

[編集]

#include <iostream>
#include <memory>
 
class Good : public std::enable_shared_from_this<Good>
{
public:
    std::shared_ptr<Good> getptr()
    {
        return shared_from_this();
    }
};
 
class Best : public std::enable_shared_from_this<Best>
{
    struct Private{ explicit Private() = default; };
 
public:
    // Constructor is only usable by this class
    Best(Private) {}
 
    // Everyone else has to use this factory function
    // Hence all Best objects will be contained in shared_ptr
    static std::shared_ptr<Best> create()
    {
        return std::make_shared<Best>(Private());
    }
 
    std::shared_ptr<Best> getptr()
    {
        return shared_from_this();
    }
};
 
struct Bad
{
    std::shared_ptr<Bad> getptr()
    {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
 
void testGood()
{
    // Good: the two shared_ptr's share the same object
    std::shared_ptr<Good> good0 = std::make_shared<Good>();
    std::shared_ptr<Good> good1 = good0->getptr();
    std::cout << "good1.use_count() = " << good1.use_count() << '\n';
}
 
void misuseGood()
{
    // Bad: shared_from_this is called without having std::shared_ptr owning the caller
    try
    {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    }
    catch (std::bad_weak_ptr& e)
    {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';
    }
}
 
void testBest()
{
    // Best: Same but cannot stack-allocate it:
    std::shared_ptr<Best> best0 = Best::create();
    std::shared_ptr<Best> best1 = best0->getptr();
    std::cout << "best1.use_count() = " << best1.use_count() << '\n';
 
    // Best stackBest; // <- Will not compile because Best::Best() is private.
}
 
void testBad()
{
    // Bad, each shared_ptr thinks it is the only owner of the object
    std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
    std::shared_ptr<Bad> bad1 = bad0->getptr();
    std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
} // UB: double-delete of Bad
 
int main()
{
    testGood();
    misuseGood();
 
    testBest();
 
    testBad();
}

実行結果の例

good1.use_count() = 2
bad_weak_ptr
best1.use_count() = 2
bad1.use_count() = 1
Bad::~Bad() called
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption

[編集] Defect reports

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 2179
(P0033R1)
C++11 enable_shared_from_this から派生した型 T が与えられた場合、以下の動作は不明確でした。
同じ T* オブジェクトから 2 つの std::shared_ptr<T> を構築する
この場合の動作は
未定義となる
LWG 2529
(P0033R1)
C++11 基となる std::weak_ptr がどのように更新されるかが不明確でした。 明確化された

[編集] 関連項目

オブジェクトの所有権を共有するセマンティクスを持つスマートポインタ
(クラステンプレート) [編集]
新しいオブジェクトを管理する共有ポインタを作成します
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)