简体   繁体   English

C ++ Lambda值无法捕获

[英]C++ lambda value can't capture

Here is my code,I want to test closure in c++ like javascript. 这是我的代码,我想像javascript一样在c ++中测试闭包。 Why the compiler yield this message? 为什么编译器会产生此消息? "testLambda.cpp: In lambda function: testLambda.cpp:8:11: error: 'a' is not captured" “ 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;
    }

You need to specify your captures in the square brackets, that's why lambdas require square brackets in the first place. 您需要在方括号中指定捕获内容,这就是为什么lambda首先需要方括号的原因。 You can capture them by reference: 您可以通过引用捕获它们:

[&a,&b,&c] (int x) ...

or by value: 或按值:

[a,b,c] (int x) ...

or mix it up: 或将其混合:

[a,&b,c] (int x) ...

Or you can just capture everything that you use: 或者,您可以捕获所有使用的内容:

[&] (int x) ... // by reference
[=] (int x) ... // by value

If you choose to capture a variable by value, but need to modify it, then you need to make it mutable: 如果选择按值捕获变量,但需要对其进行修改,则需要使其可变:

[=] (int x) mutable ...

Benjamin Lindley provided an answer about declaration of lambdas in C++. 本杰明·林德利(Benjamin Lindley)提供了有关在C ++中声明lambda的答案。

But technically speaking you cannot reproduce JavaScript closures using C++ lambdas. 但是从技术上讲,您不能使用C ++ lambda复制JavaScript闭包。

In JS outer variables that used by local function are protected by GC mechanism. 在JS中,局部函数使用的外部变量受GC机制保护。

But in C++, if you capture variables by reference, you can easily get into situation when referenced variables are destroyed and you'll get segmentation fault / access violation. 但是在C ++中,如果通过引用捕获变量,则很容易陷入破坏引用变量的情况,并且会遇到分段错误/访问冲突。

This, for example: 例如:

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

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

    std::cout<<c<<b<<std::endl;
    return 0;
}

will crash badly as after return from the returnLambda() its variables a,b and c are destroyed (their stack location is used by something else) when function f() is called. 从returnLambda()返回后,将严重崩溃,因为在调用函数f()时,其变量a,b和c被破坏(它们的堆栈位置被其他对象使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM