I'm currently using boost::asio for a project, and have to send buffers to remote endpoints. My current algorithm for sending the data looks like this:
void send_the_data(DataElement const& data)
{
auto databuf = make_shared<std::vector<uint8_t>>(data.to_bytes());
// lambda object holds a reference to the data to prevent early destruction.
asio::async_write(this->sock,
asio::buffer(databuf),
transfer_all(),
[this, databuf](size_t bt, boost::system::error_code const& ec)
{
if(ec) this->handle_error(ec);
else this->do_the_next_thing();
assert(bt = databuf->size());
// the destructor of this lambda should clean up the data buffer here,
// after it has been handled.
});
}
My logic is that the lambda capture of the shared_ptr will prevent it from being destroyed until after the async_write
is done with it, and then properly clean up the buffer once the handler has executed.
However, I'm curious if either the major compilers or the standard allow for the capture of the variable to be elided if there is no reference to it in the body of the lambda, which would lead to undefined behaviour (due to possibly accessing a dangling pointer within the async_write
call), or if the standard guarantees that all value captures will not be elided.