更改 c++ lambda 中捕获的变量的值
Changing the values of captured variables inside the c++ lambda
我正在尝试通过引用将捕获的变量递增为 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;
}
实际输出 :32765
32765
32765
32765
预期输出 :4
5
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 的原因。您尝试访问的地址处的内存已被释放,不再包含任何数据结构。
传递值有效,因为内存未释放。您正在每个点传递数据的副本;该程序不会释放这些数据,您最终会得到一个连贯的值。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用