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