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) (desde C++11)
std:: shared_ptr < T const > shared_from_this ( ) const ;
(2) (desde C++11)

Devuelve un std:: shared_ptr < T > que comparte la propiedad de * this con todos los std:: shared_ptr existentes que hacen referencia a * this .

Contenidos

Valor de retorno

std:: shared_ptr < T > ( weak_this  )

Excepciones

Si shared_from_this se llama sobre un objeto que no está previamente compartido por std::shared_ptr , std::bad_weak_ptr será lanzada por el constructor de std::shared_ptr .

Ejemplo

#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(); // comparte la propiedad del objeto con pf2
    }
    std::cout << "pf2 is gone\n";   
}

Salida:

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

Véase también

(C++11)
puntero inteligente con semántica de propiedad compartida de objetos
(plantilla de clase)