c++ - 了解 C++11 的 Lambda 中的 move 捕获

标签 c++ c++11 lambda move rvalue-reference

我对为解决 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/

相关文章:

java - 如何获取构造函数lambda的返回类型

Python 数据框使用带有 2 个变量的 lambda 函数和 if else 语句分配新列

c++ - 检查字符串的格式是否为 "coordinate/coordinate"

c++ - 如何将 CComVariant bstr 转换为 CString

c++ - 可变参数模板模板参数语法

C#:从 lambda 表达式获取链中的属性名称

c++ - C++中的进程间通信

c++ - 用内在的x86/x64 msvc替换内联程序尾调用函数结尾

c++ - 重载函数调用编译时常量

c++ - 如何在数组 <bool> 上使用位操作