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 , которые ссылаются на * this .

Содержание

Возвращаемое значение

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)
умный указатель с семантикой совместного владения объектом
(шаблон класса)