移动捕获 lambda 中的参数

cpp*_*ner 0 c++ lambda move-semantics c++17

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

我想按照在 lambda 中移动捕获中的教程来移动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
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:-

main.cpp: 在 lambda 函数中: main.cpp:10:11: 错误: 无法将类型 'B&&' 的右值引用绑定到类型 'const B' 的左值 main.cpp:5:12: 注意:初始化参数 1 of ' void f(B&&)'

我也尝试过[b=std::move(b)]但失败了(链接=通过移动捕获的 lambda 函数传递给函数)。

如何正确移动参数?

Gui*_*cot 5

移动语义仅适用于可变对象。您需要使您的 lambda 可变:

auto func_lambda = [b = std::move(b)]() mutable {
    f(std::move(b));
};
Run Code Online (Sandbox Code Playgroud)

但是,您只能调用一次这样的 lambda。如果要多次调用它,则必须生成值或使用std::exchange(b, B{})