
Christopher Kohlhoff wrote:
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.
Yes, shared_ptr is a simple method to avoid delete before using, but it isn't perfect. because it doesn't prevent the object from using other external deleted resource in the handler function. Maybe there is no perfect method for this problem I think.
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.
If I call _socket.close() in the same thread which calling io_service.run(), does the handler function always be called before close() return? But if call _socket.close() in main thread, I also don't know when the last handler function will be called and when can delete connection object safely. And in main thread, if I post another function to the io_service after I calling _socket.close(), is this function always be called after last socket handler function is called? Sorry for my poor English, I tried my best to express this clearly. Thanks, Wang Yun