更改 c++ lambda 中捕获的变量的值

Changing the values of captured variables inside the c++ lambda

本文关键字:变量 c++ lambda 更改      更新时间:2023-10-16

我正在尝试通过引用将捕获的变量递增为 lambda 函数,但无法这样做。

通过按值捕获变量,然后使 lambda 可变,我能够递增值。但是通过传递引用,增量不会应用。

也 在按值捕获的情况下,值如何在调用 inc(( 时更新。这类似于 JS 中的闭包吗?

**Capture By reference**
auto inc_count(int x){
return [&x](){
return x++;
};
};
int main()
{
auto inc = inc_count(4);
cout<<inc()<<endl;    //32765
cout<<inc()<<endl;    //32765
cout<<inc()<<endl;    //32765
cout<<inc()<<endl;    //32765
return 0;
}

**Capture by value**
auto inc_count(int x){
return [x]()mutable{
return x++;
};
};
int main()
{
auto inc = inc_count(4);
cout<<inc()<<endl;     //4
cout<<inc()<<endl;     //5
cout<<inc()<<endl;     //6
cout<<inc()<<endl;     //7
return 0;
}

实际输出 :
3276532765
32765

32765

预期输出 :
45

6
7

在第一个版本中,您将捕获对函数返回后不活动的变量的引用。在函数返回并且代码具有未定义的行为后,您有一个悬空引用。

您可以使用以下内容按引用进行捕获。

auto inc_count(int& x){
return [&x](){
return x++;
};
};

但是,您不能在main中使用int_count(4)。您必须使用一个变量,其引用可以在int_count中使用。

int main()
{
int number = 4;
auto inc = inc_count(number);
...
return 0;
}

在此函数中,您接收x作为某个参数的副本。

auto inc_count(int x){
return [&x](){
return x++;
};
};

当您从inc_count返回时,返回值&x引用的x将被销毁。这就是为什么您的值接近最大值short值 32,767 的原因。您尝试访问的地址处的内存已被释放,不再包含任何数据结构。

传递值有效,因为内存未释放。您正在每个点传递数据的副本;该程序不会释放这些数据,您最终会得到一个连贯的值。