0

I'm reading the C++11 HTTP Server example at https://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/example/cpp11/http/server/ and want to make sure I understand use of shared_ptr pervading this example. I couldn't see any direct explanation in the documentation.

I assume that the reason that connection inherits from std::enable_shared_from_this<connection>, and is then passed in a shared_ptr (the captured self) to the handler registered with the the async_read_some in connection::do_read(), is to ensure that the connection object is kept alive for as long as the asynchronous read operation requires it. The server class creates a shared_ptr to a new connection in its server::do_accept() function accordingly.

I infer therefore that if the shared_ptr based design was not used (i.e., connection object just allocated on the stack in a std::set<connection> connections_ held by connection_manager instead of std::set<connection_ptr> and only this is captured by the handler passed to socket_.async_read_some), something unpleasant could happen due to an outstanding async_read_some handler's call occurring after the connection object no longer existed.

My question (assuming my previous understanding is correct) is, how necessary is all this use of shared_ptr/shared_from_this() and what circumstance(s) would lead to such an occurrence if no shared_ptrs were used, since a stack allocated connection would live for the duration of the connection_manager/server that owns it.

TPJ
  • 179
  • 1
  • 11
  • from generic view - if some object accessed from several threads - native solution use shared_ptr (reference counting) for manage it lifetime. – RbMm Aug 11 '19 at 19:38
  • I recommend you look at the answers to [this](https://stackoverflow.com/questions/11356742/boost-async-functions-and-shared-ptrs) question. – kenba Aug 14 '19 at 09:00
  • Thanks, I think my main concern was that `shared_ptr` feels a bit intrusive, however if that is the idiomatic way to handle asynchronicity in ASIO and I haven't off the top of my head got a better alternative, then I accept that. – TPJ Aug 15 '19 at 15:34
  • Not idiomatic at all. Your primary responsibility is to manage lifetime so that when the async handler gets called, all functions/methods get called on valid objects. It doesn't matter whether you allocate objects on stack or heap, just make sure they outlive any async callbacks. Shared pointers/`enable_shared_from_this` is just one way of managing object lifetime, although usually the preferred one. – Tom Trebicky Aug 18 '19 at 20:57

0 Answers0