[英]lambda function c++ capture by value reset its values, why?
Can someone explain me why localVar after being incremented by 1 is reset back to 10? 有人可以解释一下为什么localVar增加1后会重置为10? Looks like the lambdas make copies of the capture-by-value on the stack before executing them.
看起来lambdas在执行它们之前会复制堆栈上的capture-by-value。
void lambdaTest()
{
int localVar = 10;
// Access all local variables by reference
auto byRef = [&] ()
{
cout << "localVar = " << ++localVar << endl;
};
// Access all local variables by value
auto byValue = [=] () mutable
{
cout << "localVar = " << localVar << endl;
};
byRef(); // localVar = 11
byValue(); // localVar = 10, why?
}
Yes, that's exactly what they do. 是的,这正是他们所做的。
Lambdas, internally, are structs with an operator()
set up for you. Lambdas在内部是为您设置
operator()
结构。 When you ask a lambda to capture-by-value, the struct stores a copy of any local variables that are referenced as members of the struct. 当您要求lambda按值捕获时,struct会存储作为struct成员引用的任何局部变量的副本 。 Thus, what you're seeing isn't
localVar
being reset, you're seeing the lambda's copy of localVar
. 因此,您所看到的不是
localVar
被重置,您正在看到lambda的 localVar
副本 。
Here's an example that illustrates this behavior: 这是一个说明此行为的示例:
#include <iostream>
#include <assert.h>
int main()
{
int localVar = 10;
auto byRef = [&]() {
std::cout << "byRef = " << ++localVar << '\n';
};
auto byValue = [=]() mutable {
// `mutable` lets us make changes to the *copy* of `localVar`
std::cout << "byVal = " << localVar++ << '\n';
};
byRef(); // byRef = 11 -> actual localVar is now 11
byRef(); // byRef = 12 -> actual localVar is now 12
byRef(); // byRef = 13 -> actual localVar is now 13
byValue(); // byVal = 10 -> copied localVar is now 11
byValue(); // byVal = 11 -> copied localVar is now 12
assert(localVar == 13);
}
just add another output. 只需添加另一个输出。
void lambdaTest()
{
int localVar = 10;
// Access all local variables by reference
auto byRef = [&] ()
{
cout << "localVar = " << ++localVar << endl;
};
// Access all local variables by value
auto byValue = [=] () mutable
{
cout << "localVar = " << localVar << endl;
};
byRef(); // localVar = 11
byValue(); // localVar = 10
cout <<localVar << endl; // localVar = 11
}
c++ 11 capture-by-value capture values when lambda is defined.so, lambda haven't change value outside. 当定义lambda时,c ++ 11按值捕获捕获值。因此,lambda没有更改外部值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.