C++ lambda值无法捕获

Rya*_*Liu 0 c++ lambda

这是我的代码,我想在c ++中像javascript一样测试闭包.为什么编译器会产生此消息?"testLambda.cpp:在lambda函数中:testLambda.cpp:8:11:错误:'a'未被捕获"

    #include <iostream>
    #include <functional>
    std::function<bool(int)> returnLambda(int a){
        auto b  = 1;
        auto c  = 2;

        return [&](int x)
        {   return x*(b++)+c+a == 0;};
    }
    auto f = returnLambda(21);
    int main(){
        auto c = f(1);
        auto b = f(1);

        std::cout<<c<<b<<std::endl;
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 8

你需要在方括号中指定你的捕获,这就是lambdas首先需要方括号的原因.您可以通过引用捕获它们:

[&a,&b,&c] (int x) ...
Run Code Online (Sandbox Code Playgroud)

或按价值:

[a,b,c] (int x) ...
Run Code Online (Sandbox Code Playgroud)

或混淆:

[a,&b,c] (int x) ...
Run Code Online (Sandbox Code Playgroud)

或者您可以捕获您使用的所有内容:

[&] (int x) ... // by reference
[=] (int x) ... // by value
Run Code Online (Sandbox Code Playgroud)

如果您选择按值捕获变量,但需要修改它,那么您需要使其变为可变:

[=] (int x) mutable ...
Run Code Online (Sandbox Code Playgroud)