
Hi all, I have been using Asio and Bind for a server with great success, however I just thought of something that I wanted to clarify. If I have a class method and construct a string within this method, and then call post on the IO service with a bind generated function object that takes this local std::string as one of its arguments, is the string then copied? Naturally it will be destroyed after the asynchronous invokation when the method returns, so is it just by chance that this has worked so far? Is it undefined behavior? Example: void dummy() { string final_message="some_data"; the_client->partner_sync.post( boost::bind( &deliver_message, the_client, the_client->partner, final_message) ); } deliver_message is a global function. the_client and the_client->partner are both smart pointers to instances of the client class, and partner_sync is a strand that belongs to the client class. Is this legal usage, or am I messing things up? Do I need to keep the string around until the completion handler is invoked? Or does bind take care of this? I keep the buffer around whenever I use the asynchronous sending methods in Boost Asio as this is explicitly stated in the documentation, but is this case the same? Thanks in advance for any clarifications. Kind regards, Philip Bennefall

Philip Bennefall <philip@blastbay.com> writes:
If I have a class method and construct a string within this method, and then call post on the IO service with a bind generated function object that takes this local std::string as one of its arguments, is the string then copied?
I'm pretty sure that this depends on whether the called function object takes the string by value or by reference. If it's by value, you're fine. If it's by reference, then I'd worry.
Thanks in advance for any clarifications.
Hope this helps. Best regards, Tony

On Sat, Apr 7, 2012 at 12:30 AM, Philip Bennefall <philip@blastbay.com> wrote:
string final_message="some_data"; the_client->partner_sync.post( boost::bind( &deliver_message, the_client, the_client->partner, final_message) ); ... around until the completion handler is invoked? Or does bind take care of this? I keep the buffer around whenever I use the asynchronous sending methods in Boost Asio as this is explicitly stated in the documentation, but is this case the same?
Actually, bind forces a copy of all parameters. So yes, you're cool. If you ever want to actually pass something per reference into bind you have to use boost::ref or boost::cref respectively. Cheers, Stephan
participants (3)
-
Anthony Foiani
-
Philip Bennefall
-
Stephan Menzel