std::enable_shared_from_this<T>::shared_from_this
提供: cppreference.com
<tbody>
</tbody>
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_this は enable_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>。
例
Run this code
#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
関連項目
(C++11) |
共有オブジェクト所有権のセマンティクスを持つスマートポインタ (クラステンプレート) |