預設捕獲

預設情況下,無法從 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
};