std::enable_shared_from_this
Defined in header
<memory>
| ||
template<class T > class enable_shared_from_this;
| (since C++11) | |
std::enable_shared_from_this
allows an object t
that is currently managed by astd::shared_ptr namedpt
to safely generate additional std::shared_ptr instancespt1, pt2, ...
that all share ownership of t
with pt
.
Inheriting from std::enable_shared_from_this<T>
provides the typeT
with a member function shared_from_this
. If an objectt
of type T
is managed by a std::shared_ptr<T> named pt
, then calling T::shared_from_this
will return a newstd::shared_ptr<T> that shares ownership of t
with pt
.
Note that prior to calling shared_from_this
on an object t
, there must be astd::shared_ptr that ownst
.
Also note that enable_shared_from_this
provides an alternative to an expression likestd::shared_ptr<T>(this), which is likely to result in this being destructed more than once by multiple owners that are unaware of each other.
Member functions
constructs an enabled_shared_from_this object (protected member function) | |
destroys an enable_shared_from_this object (protected member function) | |
returns a reference to this (protected member function) | |
returns a shared_ptr which shares ownership of*this (public member function) |
Notes
A common implementation for enable_shared_from_this
is to hold a weak reference (such asstd::weak_ptr) tothis. The constructors ofstd::shared_ptr detect the presence of anenable_shared_from_this
base and assign the newly created std::shared_ptr to the internally stored weak reference. Constructing astd::shared_ptr for an object that is already managed by anotherstd::shared_ptr will not consult the internally stored weak reference and thus will lead to undefined behavior.
Example
#include <memory> #include <iostream> struct Good: std::enable_shared_from_this<Good> { std::shared_ptr<Good> getptr() { return shared_from_this(); } }; struct Bad { std::shared_ptr<Bad> getptr() { return std::shared_ptr<Bad>(this); } ~Bad() { std::cout << "Bad::~Bad() called\n"; } }; int main() { // Good: the two shared_ptr's share the same object std::shared_ptr<Good> gp1(new Good); std::shared_ptr<Good> gp2 = gp1->getptr(); std::cout << "gp2.use_count() = " << gp2.use_count() << '\n'; // Bad, each shared_ptr thinks it's the only owner of the object std::shared_ptr<Bad> bp1(new Bad); std::shared_ptr<Bad> bp2 = bp1->getptr(); std::cout << "bp2.use_count() = " << bp2.use_count() << '\n'; } // UB: double-delete of Bad
Output:
gp2.use_count() = 2 bp2.use_count() = 1 Bad::~Bad() called Bad::~Bad() called *** glibc detected *** ./test: double free or corruption