std::enable_shared_from_this allows an
object t that is currently managed by a std::shared_ptr named pt to safely generate additional
std::shared_ptr instances pt1, pt2, ... that all share ownership of t with pt.
Publicly inheriting from std::enable_shared_from_this<T> provides the type T with a member function
shared_from_this. If an object t of type T is managed by a std::shared_ptr<T> named pt, then calling
T::shared_from_this will return a new std::shared_ptr<T> that shares ownership of t with pt.
1234
classhello_printer:publicstd::enable_shared_from_this<hello_printer>{public:// Main class functionvoidsay_hello(){std::cout<<"Hello, World!"<<'\n';}
12345678
staticstd::shared_ptr<hello_printer>create(){returnstd::shared_ptr<hello_printer>(newhello_printer());}private:// New objects need to be created with the factoryhello_printer()=default;};
// y2 will also point to the same object as ystd::shared_ptr<hello_printer>y2=y->shared_from_this();y2->say_hello();std::cout<<"y2.get() = "<<y2.get()<<'\n';std::cout<<"&y2 = "<<&y2<<'\n';