考虑以下代码:
void f() {
int a = 3;
[=]() {
[=] () mutable {
a = 5;
}();
}();
}
它在 Clang ( https://godbolt.org/z/IEXotM) 上编译,但不在 GCC (https://godbolt.org/z/xWXFe6) 上编译。 GCC 错误:
<source>: In lambda function:
<source>:5:15: error: assignment of read-only variable 'a'
5 | a = 5;
| ~~^~~
Compiler returned: 1
根据 https://en.cppreference.com/w/cpp/language/lambda ,
Optional sequence of specifiers.The following specifiers are allowed:
mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions
Clang 在这里的行为似乎是正确的。是这样吗?
最佳答案
如果您从引用的链接底部开始阅读,您可以阅读:
If a nested lambda m2 captures something that is also captured by the immediately enclosing lambda m1, then m2's capture is transformed as follows:
- if the enclosing lambda m1 captures by copy, m2 is capturing the non-static member of m1's closure type, not the original variable or this.
if the enclosing lambda m1 captures by reference, m2 is capturing the original variable or this.
#include <iostream> int main() { int a = 1, b = 1, c = 1; auto m1 = [a, &b, &c]() mutable { auto m2 = [a, b, &c]() mutable { std::cout << a << b << c << '\n'; a = 4; b = 4; c = 4; }; a = 3; b = 3; c = 3; m2(); }; a = 2; b = 2; c = 2; m1(); // calls m2() and prints 123 std::cout << a << b << c << '\n'; // prints 234 }
因此,您正在从封闭的 lambda 中捕获值并修改它,您也需要使其在封闭的 lambda 中可变。
关于c++ - 嵌套的 lambda 和可变关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472114/