I come across a weird behavior when switching from clang
to gcc
. clang
successfully compiles the code while gcc
reports an error. Here is a minimal example to reproduce the behavior. I have tried this with c++14
and c++17
with multiple clang
and gcc
versions.
Who is right here, clang or gcc?
struct A {
int value;
};
auto makeCallback(const A& a) {
auto callback = [aCopy = a](int i) {
[aCopy, i]() mutable { aCopy.value = i; }();
};
return callback;
}
Edit:
Changing the outer lambda to be mutable
, resolves the issue on gcc
.
clang
is right. The inner closure captures aCopy
by value, and mutating that doesn't affect the outer closure. gcc
seems to get confused by the identical name for the variable in question. You can work around this by giving it another name. Example:
auto callback = [aCopy = a](int i) {
[anotherName = aCopy, i]() mutable { anotherName.value = i; }();
};
This compiles with both clang
and gcc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With