I frequently see this pattern in code, binding shared_from_this
as the first parameter to a member function and dispatching the result using an async_*
function. Here's an example from another question:
void Connection::Receive()
{
boost::asio::async_read(socket_,boost::asio::buffer(this->read_buffer_),
boost::bind(&Connection::handle_Receive,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
The only reason to use shared_from_this()
instead of this
is to keep the object alive until the member function gets called. But unless there's some kind of boost magic somewhere, since the this
pointer is of type Connection*
, that's all handle_Receive
can take, and the smart pointer returned should be converted to a regular pointer immediately. If that happens, there's nothing to keep the object alive. And, of course, there's no pointer in calling shared_from_this
.
However, I've seen this pattern so often, I can't believe it's as completely broken as it seems to me. Is there some Boost magic that causes the shared_ptr to be converted to a regular pointer later, when the operation completes? If so, is this documented somewhere?
In particular, is it documented somewhere that the shared pointer will remain in existence until the operation completes? Calling get_pointer
on the strong pointer and then calling the member function on the returned pointer is not sufficient unless the strong pointer isn't destroyed until the member function returns.