我对为解决 C++11 lambda 中的 move 捕获而提出的解决方法有疑问。特别是,以 Meyer's book 中的示例为例:
std::vector<double> data;
...
auto func = std::bind( [](const std::vector<double>& data)
{ /*uses of data*/ },
std::move(data)
);
我的问题是:将参数“数据”声明为右值引用的后果/意义是什么?:
auto func = std::bind( [](std::vector<double>&& data)
...
为了帮助您找到答案,我将提出三点主张。请告诉我我是对还是错:
- 在这两种情况下,C++14 中包含的 move 捕获语义都得到了很好的模拟。
- 在这两种情况下,在定义“func”之后使用数据是不安全的。
- 不同之处在于,在第二种情况(右值引用)中,我们声明可调用对象(lambda)可以 move “数据”的内容。
提前致谢。
最佳答案
what would be the consequences/meaning of declaring the parameter "
data
" as an rvalue reference?
它不会编译(至少如果您尝试实际调用 func
)。 std::bind
始终将绑定(bind)参数作为左值传递,这不会绑定(bind)到右值引用。
In both cases, it is not safe to use data after the definition of "func".
data
因 move 而处于有效但未指定的状态。您可以像使用内容未知的 vector 一样使用它。
关于c++ - 了解 C++11 的 Lambda 中的 move 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30648474/