繁体   English   中英

C ++ Lambda值无法捕获

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

这是我的代码,我想像javascript一样在c ++中测试闭包。 为什么编译器会产生此消息? “ 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;
    }

您需要在方括号中指定捕获内容,这就是为什么lambda首先需要方括号的原因。 您可以通过引用捕获它们:

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

或按值:

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

或将其混合:

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

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

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

如果选择按值捕获变量,但需要对其进行修改,则需要使其可变:

[=] (int x) mutable ...

本杰明·林德利(Benjamin Lindley)提供了有关在C ++中声明lambda的答案。

但是从技术上讲,您不能使用C ++ lambda复制JavaScript闭包。

在JS中,局部函数使用的外部变量受GC机制保护。

但是在C ++中,如果通过引用捕获变量,则很容易陷入破坏引用变量的情况,并且会遇到分段错误/访问冲突。

例如:

#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;
}

从returnLambda()返回后,将严重崩溃,因为在调用函数f()时,其变量a,b和c被破坏(它们的堆栈位置被其他对象使用)。

暂无
暂无

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

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