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

Gibt einen std:: shared_ptr < T > zurück, der die Eigentümerschaft von * this mit allen bestehenden std:: shared_ptr teilt, die auf * this verweisen.

Inhaltsverzeichnis

Rückgabewert

std:: shared_ptr < T > ( weak_this  )

Exceptions

Wenn shared_from_this auf einem Objekt aufgerufen wird, das nicht zuvor durch std::shared_ptr geteilt wurde, wird std::bad_weak_ptr vom Konstruktor des std::shared_ptr geworfen.

Beispiel

#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(); // teilt sich den Besitz des Objekts mit pf2
    }
    std::cout << "pf2 is gone\n";   
}

Ausgabe:

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

Siehe auch

(C++11)
Intelligenter Zeiger mit Shared-Object-Ownership-Semantik
(Klassentemplate)