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 이후)

std:: shared_ptr < T > 를 반환하며, 이는 * this 의 소유권을 std:: shared_ptr 를 참조하는 모든 기존 객체와 공유합니다.

목차

반환값

std:: shared_ptr < T > ( weak_this  )

예외

만약 shared_from_this 가 이전에 std::shared_ptr 에 의해 공유되지 않은 객체에서 호출되면, std::bad_weak_ptr std::shared_ptr 생성자에 의해 throw됩니다.

예제

#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)
공유 객체 소유권 의미론을 가진 스마트 포인터
(클래스 템플릿)