Skip to content

Shared from this

Shared from this

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.

1
2
3
4
class hello_printer : public std::enable_shared_from_this<hello_printer> {
  public:
    // Main class function
    void say_hello() { std::cout << "Hello, World!" << '\n'; }

1
2
3
4
5
6
7
8
    static std::shared_ptr<hello_printer> create() {
        return std::shared_ptr<hello_printer>(new hello_printer());
    }

  private:
    // New objects need to be created with the factory
    hello_printer() = default;
};

1
2
3
4
auto y = hello_printer::create();
y->say_hello();
std::cout << "y.get() = " << y.get() << '\n';
std::cout << "&y = " << &y << '\n';

1
2
3
4
5
// y2 will also point to the same object as y
std::shared_ptr<hello_printer> y2 = y->shared_from_this();
y2->say_hello();
std::cout << "y2.get() = " << y2.get() << '\n';
std::cout << "&y2 = " << &y2 << '\n';

1
2
3
4
auto z = hello_printer::create();
z->say_hello();
std::cout << "z.get() = " << z.get() << '\n';
std::cout << "&z = " << &z << '\n';

Share Snippets