Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 657
Elvis Oric Avatar asked Sep 13 '19 08:09

Elvis Oric


1 Answers

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.

like image 130
lubgr Avatar answered Nov 03 '22 07:11

lubgr