Is that code safe?
class C : public std::enable_shared_from_this<C> {
void start() {
boost::asio::async_write(socket_, boost::asio::buffer(message_),
std::bind(&tcp_connection::handle_write, shared_from_this(),
_1, _2));
};
// ...
};
class D {
void start()
{
std::shared_ptr<C> cptr = std::make_shared<C>(); // (1)
cptr->start();
} // (2)
};
If the message is long, the async_write operation can take a long time.
There is only one shared_ptr pointing to the C object at point (1). start() is called, start() finishes and at (2) the variable cptr goes out of scope and is destroyed.
When async_write has finished the writing operation, the callback is called; this causes a crash because shared_from_this() tries to make a shared_ptr to a non-existent object.
Is this description of what would happen correct?
No, you are not right.
The call to shared_from_this() happens before start returns. A copy of the resulting shared_ptr is held by the result of bind.
So when you reach (2) only one of the two references to the object has gone, and it remains alive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With