0
votes

MCVE : http://coliru.stacked-crooked.com/a/ef442eca9b74c8f1

I want to move parameter in lambda function by following a tutorial in Move capture in lambda.

#include <string>
#include <iostream>
#include <functional>
class B{};
void f(B&& b){}
int main(){
    B b;
    auto func_lambda=[b{std::move(b)}](){
        //f(std::move(b));  // also fails
        f(b); // also fails
    };
    //: std::function<void()> func_cache=func_lambda(); 
    //       will be stored and called after 'b' is out of scope
}

I got this error :-

main.cpp: In lambda function: main.cpp:10:11: error: cannot bind rvalue reference of type 'B&&' to lvalue of type 'const B' main.cpp:5:12: note: initializing argument 1 of 'void f(B&&)'

I have also tried [b=std::move(b)] but fail (link= Passing a lambda with moved capture to function).

How to move the parameter correctly?

1
Notice that creating such lambda is "risky", as calling twice might call function with move-from object.Jarod42

1 Answers

5
votes

Move semantics only work on mutable objects. You will need to make your lambda mutable:

auto func_lambda = [b = std::move(b)]() mutable {
    f(std::move(b));
};

However you can only call such lambda once. If you want to call it multiple time, you'll have to generate values or use std::exchange(b, B{})