std::enable_shared_from_this
From Cppreference
Defined in header <memory>
|
||
template< class T > class enable_shared_from_this;
|
(since C++11) | |
A class T can inherit from std::enable_shared_from_this<T> to inherit the shared_from_this member functions that obtain a std::shared_ptr that manages the this object, sharing its ownership with any existing std::shared_ptr's that manage the same object.
Contents |
[edit] Member functions
constructs an enabled_shared_from_this object (public 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) |
[edit] Notes
Common implementation for enable_shared_from_this is to hold a weak reference, such as std::weak_ptr, to this. The constructors of std::shared_ptr detect presence of a enable_shared_from_this base and instead of assuming the pointer is not managed by anyone else, they detect other owners through that weak reference.
[edit] 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
[edit] See also
(C++11)
|
smart pointer with shared object ownership semantics (class template) |