我目前正在为一个项目使用boost::asio,并且必须向远程端点发送缓冲区。我当前发送数据的算法如下:
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.
});
}
我的逻辑是,共享ptr的lambda捕获将防止它在
async_write
处理完毕,然后在处理程序执行后正确清理缓冲区。
但是,我很好奇,如果lambda主体中没有引用变量,那么主要编译器或标准是否允许省略变量的捕获,这将导致未定义的行为(因为可能访问
或者如果标准保证所有捕获的值都不会被忽略。