Lambda捕获C ++ 14 [英] Lambda Captures C++14
问题描述
我遇到了类似这样的符号:
I've encountered a notation like:
int x = 4;
auto y = [&r = x, x = x+1]()->int {
r += 2;
return x+2;
}();
您能解释一下这句话吗?我是C ++ 03的用户,最近升级到C ++ 11。从今天开始,我开始使用C ++ 14并遇到了该代码段。
Can you explain this statement? I was a user of C++03 and recently upgraded to C++11. From today I starts C++14 and encountered this snippet.
谢谢!
推荐答案
感谢@chris提供维基百科参考。我发现的是-
Thanks @chris for the wikipedia reference. What I found is -
这是一个很好的解释,他们不知道旧的Lambda C ++ 11捕获
在C ++ 14中:
C ++ 11 lambda函数捕获通过值复制或引用在其外部范围
中声明的变量。这意味着
lambda的值成员不能是仅移动类型。 C ++ 14允许使用任意表达式初始化捕获的成员
。这样既可以通过
的值移动来捕获,也可以声明lambda的任意成员,而无需
在外部范围内具有相应命名的变量。
C++11 lambda functions capture variables declared in their outer scope by value-copy or by reference. This means that value members of a lambda cannot be move-only types. C++14 allows captured members to be initialized with arbitrary expressions. This allows both capture by value-move and declaring arbitrary members of the lambda, without having a correspondingly named variable in an outer scope.
这可以通过使用初始化程序表达式来完成:
This is done via the use of an initializer expression:
auto lambda = [value = 1] {return value;};
lambda函数 lambda
将返回1,这就是初始化
的 value
的值。声明的捕获从
初始值设定项表达式中推断出类型,就好像通过 auto
来实现。
The lambda function lambda
will return 1, which is what value
was
initialized with. The declared capture deduces the type from the
initializer expression as if by auto
.
通过使用标准
std :: move
函数来移动捕获:
This can be used to capture by move, via the use of the standard
std::move
function:
std::unique_ptr<int> ptr(new int(10));
auto lambda = [value = std::move(ptr)] {return *value;};
上面的表达式将x更新为6,并将y初始化为7。
So the above expression updates x to 6, and initializes y to 7.
这篇关于Lambda捕获C ++ 14的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!