默认捕获
默认情况下,无法从 lambda 主体中访问未在捕获列表中明确指定的局部变量。但是,可以隐式捕获 lambda 体命名的变量:
int a = 1;
int b = 2;
// Default capture by value
[=]() { return a + b; }; // OK; a and b are captured by value
// Default capture by reference
[&]() { return a + b; }; // OK; a and b are captured by reference
显式捕获仍然可以与隐式默认捕获一起完成。显式捕获定义将覆盖默认捕获:
int a = 0;
int b = 1;
[=, &b]() {
a = 2; // Illegal; 'a' is capture by value, and lambda is not 'mutable'
b = 2; // OK; 'b' is captured by reference
};