有什么方法可以从外部更改 lambda 中通过复制捕获的变量吗?
例子:
#include <iostream>
int main() {
int x = 3;
auto f = [x]() { std::cout << x << std::endl; };
// is there anything I can do here to make f print 4?
f();
}
如果可以的话,感觉真的很脏。有什么令人信服的理由让我什至不应该考虑这样做吗?
最佳答案
#include <iostream>
int main()
{
int x = 3;
auto f = [&x]() { std::cout << x << std::endl; };
x++;
f();
}
关于C++:从外部更改在 lambda 中捕获的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005843/