名前空間
変種
操作

std::enable_shared_from_this<T>::shared_from_this

提供: cppreference.com
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
動的メモリ管理
スマートポインタ
(C++11)
(C++11)
(C++11)
(C++17未満)
(C++11)
アロケータ
メモリリソース
未初期化記憶域
ガベージコレクションサポート
その他
(C++20)
(C++11)
(C++11)
C のライブラリ
低水準のメモリ管理
 
 
std::shared_ptr<T> shared_from_this();
(1)
std::shared_ptr<T const> shared_from_this() const;
(2)

*this を参照するすべての既存の std::shared_ptr*this の所有権を共有する std::shared_ptr<T> を返します。

実質的に std::shared_ptr<T>(weak_this) を実行します。 ただし weak_thisenable_shared_from_this のプライベートな std::weak_ptr<T> 型の mutable メンバです。

目次

[編集] ノート

shared_from_this は、すでに共有されている、つまり、すでに std::shared_ptr によって管理されているオブジェクトに対してのみ、呼ぶことができます (特に、 *this の構築中に shared_from_this を呼ぶことはできません)。

そうでなければ、動作は未定義です (C++17未満)(デフォルト構築された weak_this からの shared_ptr のコンストラクタによって) std::bad_weak_ptr が投げられます (C++17以上)

[編集] 戻り値

既存の std::shared_ptr*this の所有権を共有する std::shared_ptr<T>

[編集]

#include <iostream>
#include <memory>
 
struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; } 
    std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};
 
int main() {
    Foo *f = new Foo;
    std::shared_ptr<Foo> pf1;
 
    {
        std::shared_ptr<Foo> pf2(f);
        pf1 = pf2->getFoo();  // shares ownership of object with pf2
    }
 
    std::cout << "pf2 is gone\n";   
}

出力:

Foo::Foo
pf2 is gone
Foo::~Foo

[編集] 関連項目

共有オブジェクト所有権のセマンティクスを持つスマートポインタ
(クラステンプレート) [edit]