简体   繁体   English

了解Lambdas for C ++ 11中的移动捕获

[英]Understanding Move Capture in Lambdas for C++11

I have a question regarding the workaround proposed in order to address move capture in C++11 lambdas. 我有一个关于为解决C ++ 11 lambdas中的移动捕获而提出的解决方法的问题。 In particular, taking the example from Meyer's book : 特别是,以迈耶(Meyer)的书为例:

std::vector<double> data;
... 
auto func = std::bind( [](const std::vector<double>& data) 
                       { /*uses of data*/ },
                       std::move(data)
                     );

My question is: what would be the consequences/meaning of declaring the parameter "data" as an rvalue reference?: 我的问题是:将参数“ data”声明为右值引用的结果/含义是什么?

auto func = std::bind( [](std::vector<double>&& data)
...

To help you guide the answer, I'll make three claims. 为了帮助您指导答案,我将提出三项主张。 Please tell me if I'm right or wrong: 请告诉我我是对还是错:

  • In both cases, the move capture semantics included in C++14 are well emulated. 在这两种情况下,都很好地模拟了C ++ 14中包含的移动捕获语义。
  • In both cases, it is not safe to use data after the definition of "func". 在两种情况下,在定义“ func”之后使用数据都是不安全的。
  • The difference is that in the second case (rvalue reference), we are stating that the callable object (the lambda) could move the contents of "data". 不同之处在于,在第二种情况下(右值引用),我们声明可调用对象(lambda)可以移动“数据”的内容。

Thanks in advance. 提前致谢。

what would be the consequences/meaning of declaring the parameter " data " as an rvalue reference? 将参数“ data ”声明为右值引用的结果/含义是什么?

It won't compile (at least if you attempt to actually call func ). 它不会编译(至少如果您尝试实际调用func )。 std::bind always pass bound arguments as lvalues, which won't bind to the rvalue reference. std::bind始终将绑定参数作为左值传递,而不会绑定到右值引用。

In both cases, it is not safe to use data after the definition of "func". 在两种情况下,在定义“ func”之后使用数据都是不安全的。

data is left in a valid but unspecified state by the move. data保留为有效但未指定的状态。 You can use it the same way you use a vector whose contents are unknown. 您可以使用与内容未知的向量相同的方式来使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM