【发布时间】:2021-10-09 04:04:51
【问题描述】:
如下例,我定义了 2 个变量 x 和 y。当我两次调用 lambda 函数时,它似乎不会破坏副本。来自11.14 — Lambda captures | Learn C++ - Learn C++,它说:
因为捕获的变量是 lambda 对象的成员,所以它们的值会在对 lambda 的多次调用中保持不变!
C++ 如何管理 lambda 函数的内存?
int main() {
int x = 1;
static int y = 1;
auto fun = [=]() mutable{
x++;
y++;
cout<<"Inside:\t\t";
cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
};
for (int i = 0; i<2; i++) {
fun();
cout<<"Outside:\t";
cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl<<endl;
}
}
输出:
Inside: x:2 y:2
Outside: x:1 y:2
Inside: x:3 y:3
Outside: x:1 y:3
【问题讨论】: