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

Retourne un std:: shared_ptr < T > qui partage la propriété de * this avec tous les std:: shared_ptr existants qui référencent * this .

Table des matières

Valeur de retour

std:: shared_ptr < T > ( weak_this  )

Exceptions

Si shared_from_this est appelé sur un objet qui n'est pas préalablement partagé par std::shared_ptr , std::bad_weak_ptr est levé par le constructeur de std::shared_ptr .

Exemple

#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(); // partage la propriété de l'objet avec pf2
    }
    std::cout << "pf2 is gone\n";   
}

Sortie :

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

Voir aussi

(C++11)
pointeur intelligent avec sémantique de propriété partagée d'objet
(modèle de classe)