捕获列表中的C ++ lambda复制值 [英] C++ lambda copy value in capture-list
问题描述
我有一个程序如下:
int main()
{
int val = 4;
auto add = [val](int a)->int{
val += 2;
return a+val;
};
cout << add(3) << endl;
cout << val << endl;
return 0;
}
Xcode中存在编译错误:无法分配给通过复制捕获的变量
There's a compiling error in Xcode: Cannot assign to a variable captured by copy in a non-mutable lambda.
我的问题是:如果我们选择使用副本(使用 =或值名称),则不能为该值分配一个是新值还是更改?
My question is: if we choose to use the copy (using "=" or value name), can't this value be assigned a new value or changed?
推荐答案
在lambda中,默认情况下捕获的变量是不可变的。这并不取决于捕获的变量或捕获变量的方式。而是将闭包类型的函数调用运算符声明为 const
:
Inside a lambda, captured variables are immutable by default. That doesn't depend on the captured variables or the way they were captured in any way. Rather, the function call operator of the closure type is declared const
:
函数调用运算符或运算符模板声明为
const
(9.3.1),当且仅当lambda表达式的
parameter-declaration-子句后没有mutable
。
因此,如果您想使捕获的变量在体内可修改,只需将lambda更改为
Therefore, if you want to make the captured variables modifiable inside the body, just change the lambda to
auto add = [val] (int a) mutable -> int {
val += 2;
return a+val;
};
因此删除了 const
指定符。
这篇关于捕获列表中的C ++ lambda复制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!