Search code examples
c++c++11lambdamovervalue-reference

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. In particular, taking the example from Meyer's book:

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?:

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.
  • In both cases, it is not safe to use data after the definition of "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".

Thanks in advance.


Solution

  • what would be the consequences/meaning of declaring the parameter "data" as an rvalue reference?

    It won't compile (at least if you attempt to actually call func). std::bind always pass bound arguments as lvalues, which won't bind to the rvalue reference.

    In both cases, it is not safe to use data after the definition of "func".

    data is left in a valid but unspecified state by the move. You can use it the same way you use a vector whose contents are unknown.