Re: [asio-users] this vs shared_from_this() in examples
Brought to you by:
chris_kohlhoff
From: Amir T. <zg...@ya...> - 2012-02-21 18:04:52
|
OK thanks Igor and Yuri. I understand now. Basically io_service::stop() or the io_service must go out of scope before the class destructor (for which the methods are bound) is called. That ensures no methods tried to get call with a destroyed object. ________________________________ From: Igor R <boo...@gm...> To: Amir Taaki <zg...@ya...>; asi...@li... Sent: Tuesday, February 21, 2012 10:07 AM Subject: Re: [asio-users] this vs shared_from_this() in examples > In my project ( http://gitorious.org/libbitcoin/libbitcoin ), I just > realised today I have a problem with circular references. When I started, > someone advised me to just use shared_ptr for bind and never use this. > Assuming asio is fine with this, I didn't question that logic. However now > I'm checking and seeing my destructors never get called. > > Looking through the boost asio examples, I see bind is used with this and > shared_from_this() variously. I cannot see any pattern to it? What are the > rules of thumb for when to use this? Why can I not just use this for > everything? Would you pass this to std::bind when you know that the > primitives inside it (like the strand if you're using strand post) are > destroyed before the class? > > What happens then when I use strand.wrap(std::bind(&foo::memfunc, this, ...)) and pass that elsewhere? The question is how you ensure that the object bound to your completion handler will outlive the async operation. Binding shared_ptr to "this" is the most simple and robust way to provide such guarantee in a complex design, but in some trivial cases it can be unnecessary -- these are probably the cases you saw in asio examples. As for circular references, this issue is usually solved by means of using weak_ptr in one direction. |