0

Look at the second answer here: What is the need for enable_shared_from_this?

it says: "Short answer: you need enable_shared_from_this when you need to use inside the object itself existing shared pointer guarding this object.

Out of the object you can simply assign and copy a shared_ptr because you deal with the shared_ptr variable as is."

and later down in the last line it says: "And when and why one can need a shared pointer to this instead of just this it is quite other question. For example, it is widely used in asynchronous programming for callbacks binding."

Here in this post I want to ask exactly this other question. What is an use case for "enable_shared_from_this" and "shared_from_this"?

sanjivgupta
  • 396
  • 3
  • 12

1 Answers1

1

A simple use-case would be to ensure this survives till the end of some asynchronous, or delayed operation:

class My_type : public std::enable_shared_from_this<My_type> {

public:
  void foo() {}

  void perform_foo() {
    auto self = shared_from_this();
    std::async(std::launch::async, [self, this]{ foo(); }); 
  }
};

boost::asio uses this technique a lot in their examples: https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/example/cpp11/allocation/server.cpp