|
Boost Users : |
From: Christopher Kohlhoff (chris_at_[hidden])
Date: 2006-09-17 07:31:24
Hi Wang Yun,
Wang Yun <a_hao_at_[hidden]> wrote:
> Then I delete the Connection object in main thread, the
> receive operation will be cancelled and the receiveHandler()
> will be called with errcode
> boost::asio::error::operation_aborted, but at that time, the
> Connection object has been deleted, calling receiveHandler()
> will crash if it access the object's data member.
If you're in the destructor and you still have outstanding
operations then it's already too late. Your program needs to
ensure that any objects referred to by the handler stay valid
until the handler is called, and that includes the Connection
object referred to by the bound-in `this' pointer.
> Are there any easier method to do this?
I find it's usually simplest to use shared_ptr together with
enable_shared_from_this to ensure that your Connection object
stays alive while there are outstanding operations. Have a look
at the Daytime.3 tutorial program for a small example.
If you do need the ability to stop a connection, add a member
function to your Connection class that closes the socket. When
you call this function the operations are cancelled, and the
Connection object is destroyed only after all of the associated
async operations handlers have been called.
Cheers,
Chris
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net