[bind10-dev] Lifetime management of an object which holds asynchronous handler

Yoshitaka Aharen aharen at jprs.co.jp
Tue Jun 7 10:31:57 UTC 2011


Hello,

As Jinmei-san suggested me in ticket #957, I'd like to introduce a
method using boost::enable_shared_from_this to manage the lifetime of an
object which holds asynchronous handler.

Before freeing an object, we must make sure it is not used. However it
is not easy to ensure that the handler of asynchronous operation will
not be called any more. This method simplifies the resource management
by using shared_ptr.

At a time to register a function as a handler of asynchronous operation,
pass a function bound with a shared_ptr to the object itself by using
shared_from_this(). Ownership of an object is shared with asynchronous
library, so the object will be destroyed in case there are no more
pending handler calls and no one holds a shared_ptr to the object.

The object have to inherit from boost::enable_shared_from_this and it
have to be managed by shared_ptr.

This method can be seen in the asio tutorial:
http://think-async.com/asio/asio-1.4.8/doc/asio/tutorial/tutdaytime3.html#asio.tutorial.tutdaytime3.the_tcp_connection_class

And also in sample code:
http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/http/server/connection.cpp

I hope it is useful for our asynchronous code.

Thanks,

-- 
Yoshitaka Aharen <aharen at jprs.co.jp>
Japan Registry Services Co., Ltd.





More information about the bind10-dev mailing list