代码之家  ›  专栏  ›  技术社区  ›  cppBeginner

lambda中参数的移动捕捉

  •  -1
  • cppBeginner  · 技术社区  · 4 年前

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

    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
    }
    

    我有个错误:-

    错误:无法将“B&类型的右值引用绑定到“const B”类型的左值 主.cpp:5:12:注意:正在初始化“void f(B&)”的参数1

    我也试过了 [b=std::move(b)] Passing a lambda with moved capture to function ).

    1 回复  |  直到 4 年前
        1
  •  3
  •   Guillaume Racicot    4 年前

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