std::enable_shared_from_this<T>::shared_from_this

From cppreference.com
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
Dynamic memory management
Smart pointers
(C++11)
(C++11)
(C++11)
(until C++17)
(C++11)
(C++23)
Allocators
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
(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)
Miscellaneous
(C++20)
(C++11)
(C++11)
 
 
std::shared_ptr<T> shared_from_this();
(1)
std::shared_ptr<T const> shared_from_this() const;
(2)

Returns a std::shared_ptr<T> that shares ownership of *this with all existing std::shared_ptr that refer to *this.

Effectively executes std::shared_ptr<T>(weak_this), where weak_this is the private mutable std::weak_ptr<T> member of enable_shared_from_this.

Notes

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr (in particular, shared_from_this cannot be called during construction of *this).

Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

Return value

std::shared_ptr<T> that shares ownership of *this with pre-existing std::shared_ptrs

Example

#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";   
}

Output:

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

See also

smart pointer with shared object ownership semantics
(class template)