Namespaces
Variants

std::enable_shared_from_this<T>:: shared_from_this

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
std:: shared_ptr < T > shared_from_this ( ) ;
(1) (C++11以降)
std:: shared_ptr < T const > shared_from_this ( ) const ;
(2) (C++11以降)

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

目次

戻り値

std:: shared_ptr < T > ( weak_this  )

例外

shared_from_this が、事前に std::shared_ptr によって共有されていないオブジェクトに対して呼び出された場合、 std::shared_ptr のコンストラクタによって std::bad_weak_ptr がスローされます。

#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)
共有オブジェクト所有権セマンティクスを持つスマートポインタ
(クラステンプレート)