编译器希望我的lvalue成为一个rvalue引用,我不明白为什么。
我的问题是:
我认为这是因为lambda捕获,但是请看下面这个简化的工作流:
void read_socket()
{
std::vector<std::tuple<unsigned long long, std::vector<unsigned char>>> tupleByteVector_content;
read_socket_readSome(tupleByteVector_content, [this, &tupleByteVector_content]() {
//use tuple vector
});
}
//catch the tuple vector by reference
void read_socket_readSome(std::vector<std::tuple<unsigned long long, const std::shared_ptr<Session>& session, std::vector<unsigned char>>> & tupleByteVector_content, std::function<void()> && continueReadFunction)
{
//Read data length from a asio socket
std::shared_ptr<asio::streambuf> len_buffer = std::make_shared<asio::streambuf>();
asio::async_read(session->connection->socket->next_layer(), *len_buffer, asio::transfer_exactly(1), [&,
this, session, len_buffer, tupleByteVector_content, continueReadFunction](const error_code& ec, std::size_t bytes_transferred) {
//the first value I want to save
unsigned long long dataLen = BytesToLength(len_buffer);
//Read data from a asio socket
std::shared_ptr<asio::streambuf> data_buffer = std::make_shared<asio::streambuf>();
asio::async_read(session->connection->socket->next_layer(), *data_buffer, asio::transfer_exactly(dataLen), [&, this, dataLen, data_buffer, tupleByteVector_content, session, continueReadFunction](const error_code& ec, std::size_t bytes_transferred) {
//ERROR HERE: ----------->
std::tuple<unsigned long long, std::vector<unsigned char>> t =
std::make_tuple<unsigned long long, std::vector<unsigned char>>(
dataLen, // ERROR C2664, cant convert argument 1 from "const unsigned __int64" to "unsigned __int64 &&"
{ asio::buffers_begin(data_buffer->data()), asio::buffers_end(data_buffer->data()) });
//ERROR HERE: <-----------
tupleByteVector_content.push_back(t);
continueReadFunction();
});
});
}编辑:我能够编译这个元组:
std::tuple<unsigned long long, std::vector<unsigned char>> t = { dataLen, { asio::buffers_begin(data_buffer->data()), asio::buffers_end(data_buffer->data()) } };但是,向量的push_back给出了错误: error C2663:. ::push_back":对于2个重载,这个指针没有转换(从我自己自由翻译成英语)。
发布于 2020-07-14 12:43:50
dataLen被视为const,因为您按值捕获它:[&,这个,dataLen,^^
默认情况下,为闭包生成的函数调用操作符被标记为const,因此在const方法中只能读取数据。除非将mutable添加到lambda的定义中,否则不允许进行修改。
make_tuple时,您应该依赖于模板参数演绎,而不是像您所做的那样以显式方式放置类型。你的问题的简短版本:int i;std::tuple t= std::make_tuple(i);
i被命名为object,所以它是lvalue。通过make_tuple<int>,您可以使make_tuple签名看起来像:make_tuple(int&&)。这是编译器抱怨的地方,因为i作为lvalue不能绑定到rvalue引用。通过参数推导,推导出make_tuple的参数为:int&,在这种情况下,i可以被约束。
push_back on vector无法工作,因为您再次按值捕获向量。push_back修改对象,在调用const对象时不允许这样做。你应该以参考的方式捕捉它。
https://stackoverflow.com/questions/62891679
复制相似问题