Can someone explain me why localVar after being incremented by 1 is reset back to 10? Looks like the lambdas make copies of the capture-by-value on the stack before executing them.
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?
}
答案 0 :(得分:3)
是的,这正是他们所做的。
内部的Lambdas是为operator()
设置的结构。当您要求lambda按值捕获时,struct会存储作为struct成员引用的任何局部变量的 copy 。因此,您所看到的不是localVar
被重置,您看到 lambda的副本 localVar
。
以下是一个说明此行为的示例:
#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);
}
答案 1 :(得分:0)
只需添加另一个输出。
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定义lambda时的按值捕获捕获值。因此,lambda避免在外部更改值。