Elvis Oric
Elvis Oric

Reputation: 1364

Modifying captured parameters in nested lambda: gcc vs clang?

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.

Upvotes: 5

Views: 129

Answers (1)

lubgr
lubgr

Reputation: 38287

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.

Upvotes: 7

Related Questions