[Asio] Is shared_ptr with async_send_to ok?

View: New views
2 Messages — Rating Filter:   Alert me  

[Asio] Is shared_ptr with async_send_to ok?

by Dylan Klomparens :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I'm using a UDP socket to send data asynchronously. I know I need to preserve the data in a buffer until the async write is complete. Can I use a shared_ptr to accomplish this? Basically, my question is, will async_send_to keep a copy of my shared_ptr so that the data doesn't get deleted? Do I need to use a particular overload of the boost::asio::buffer function to ensure that a copy of the shared_ptr is stored?

Here is an example:

boost::asio::streambuf Buffer;
// ... buffer is filled with data ...
int BufferSize = Buffer.size();
boost::shared_ptr<unsigned char> SharedBuffer(new unsigned char[BufferSize]);
Buffer.sgetn(*SharedBuffer, BufferSize);
Buffer.consume(BufferSize);
Socket.async_send_to(boost::asio::buffer(*SharedBuffer, BufferSize), DestinationEndpoint, boost::bind(&MyClass::OnPacketSent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
// Shared buffer goes out of scope here, immediately!

_______________________________________________
Boost-users mailing list
Boost-users@...
http://lists.boost.org/mailman/listinfo.cgi/boost-users

Re: [Asio] Is shared_ptr with async_send_to ok?

by Igor R :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> Socket.async_send_to(boost::asio::buffer(*SharedBuffer, BufferSize), DestinationEndpoint, boost::bind(&MyClass::OnPacketSent, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
> // Shared buffer goes out of scope here, immediately!


You do not copy SharedBuffer, so it's destroyed when goes out of
scope. If you want SharedBuffer to outlive the handler, you can store
the shared_ptr within the handler, like this:

// UNTESTED!
using boost::bind;
using boost::protect;
Socket.async_send_to(buffer(*SharedBuffer, BufferSize), DestinationEndpoint,
bind(protect(bind(&MyClass::OnPacketSent, this, _1, _2)), _1, _2,
SharedBuffer)); // you can revert back to the asio placeholders
_______________________________________________
Boost-users mailing list
Boost-users@...
http://lists.boost.org/mailman/listinfo.cgi/boost-users