我正在学习 C++11 新函数 lambda 函数,有点困惑。 我看过了
[] Capture nothing (or, a scorched earth strategy?)
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy
[=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference
[bar] Capture bar by making a copy; don't copy anything else
[this] Capture the this pointer of the enclosing class
我的问题是捕获变量到底是什么意思,返回值有什么区别,如果你想捕获一个变量,你必须正确地返回它?
例如:
[] () { int a = 2; return a; }
为什么不是
int [] () { int a = 2; return a; }
最佳答案
您可以“捕获”属于封闭函数的变量。
void f() {
int a=1;
// This lambda is constructed with a copy of a, at value 1.
auto l1 = [a] { return a; };
// This lambda contains a reference to a, so its a is the same as f's.
auto l2 = [&a] { return a; };
a = 2;
std::cout << l1() << "\n"; // prints 1
std::cout << l2() << "\n"; // prints 2
}
如果需要,您可以返回捕获的变量,也可以返回其他内容。返回值与捕获无关。
关于c++ - Lambda 函数捕获变量与返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835154/