Reference

class template
<memory>

std::enable_shared_from_this

template <class T> class enable_shared_from_this;
Enable shared_from_this
Base class that enables the shared_from_this member function in derived classes.

The class provides functionality that allows objects of derived classes to create instances of shared_ptr pointing to themselves and sharing ownership with existing shared_ptr objects.

Notice that simply returning shared_ptr<T>(this) would be problematic, since that would create a different ownership group.

Template parameters

T
Full type of the pointed class (generally the final class inheriting from this).
The shared_ptr objects created will be of type shared_ptr<T>.

Protected member functions

(constructor)
Construct enable_shared_from_this (protected member function)
(destructor)
Destroy enable_shared_from_this (protected member function)
operator=
Assign enable_shared_from_this (protected member function)

Public member functions

shared_from_this
Get shared_ptr from *this (public member function)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// enable_shared_from_this example
#include <iostream>
#include <memory>
struct C : std::enable_shared_from_this<C> { };
int main () {
 std::shared_ptr<C> foo, bar;
 foo = std::make_shared<C>();
 bar = foo->shared_from_this();
 if (!foo.owner_before(bar) && !bar.owner_before(foo))
 std::cout << "foo and bar share ownership";
 return 0;
}

Output:
foo and bar share ownership

AltStyle によって変換されたページ (->オリジナル) /