https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94624
Bug ID: 94624
Summary: Nested lambda mutable capture of outer lambda
non-mutable capture is not allowed
Product: gcc
Version: tree-ssa
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: cuzdav at gmail dot com
Target Milestone: ---
An inner mutable lambda with a simple copy-capture of the outer lambda's
immutable variable is not allowed to be modified.
This applies to all versions of g++ since mutable lambdas were introduced.
Live example
https://godbolt.org/z/RkMeYL
Full source code to reproduce:
////////////////////////////////////////////////
template <typename F> void foo(F const&) {}
template <typename F> void bar(F const&) {}
void bad() {
int x = 5;
foo([x]() {
bar([x]() mutable {
x = 10; // << modify local copy in mutable lambda should be ok
});
});
}
////////////////////////////////////////////////
In lambda function:
8:15: error: assignment of read-only variable 'x'
8 | x = 10;
| ~~^~~~
Compiler returned: 1
Adding "mutable" to the outer lambda works around this, so somehow the
read-only behavior in the outer lambda is leaking into the inner lambda, even
though it is a simple copy and the underlying type is "int".
Additionally, clang accepts this all the way back to version 5.