我遇到了这样一种记号:
int x = 4;
auto y = [&r = x, x = x+1]()->int {
r += 2;
return x+2;
}();
你能解释一下这个语句吗?我之前使用的是C++03,最近升级到了C++11。从今天开始我开始使用C++14,并遇到了这段代码片段。
谢谢!
我遇到了这样一种记号:
int x = 4;
auto y = [&r = x, x = x+1]()->int {
r += 2;
return x+2;
}();
你能解释一下这个语句吗?我之前使用的是C++03,最近升级到了C++11。从今天开始我开始使用C++14,并遇到了这段代码片段。
谢谢!
感谢 @chris 提供的 wikipedia 参考资料。我发现的是 -
这里有一个很好的解释,适用于不了解 C++11 旧 lambda 捕获的人
在 C++14 中:
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;};
The lambda function
lambda
will return 1, which is whatvalue
was initialized with. The declared capture deduces the type from the initializer expression as if byauto
.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;};
y
被初始化为7
,因为它是一个lambda函数。 - tgmathy
被初始化。 - Ben Hymersint x = 4;
auto y = [&r = x, x = x+1]()->int {
r += 2; //r=6
return x+2;//5+2
};
cout<<y()<<endl; // this will print 7