https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106508

            Bug ID: 106508
           Summary: Extra warnings with lambda captures
           Product: gcc
           Version: 11.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ozixtheorange at gmail dot com
  Target Milestone: ---

The following will not work, because `this` needs to be captured to access
`member`. Seems like GCC should be able to detect that `member` is a class
member and warn that `this` is not being captured:

int outer;
struct A{
  int member = 0;
  auto fn(){
     return [&]{
       outer = member; // invalid
     };
  }
};

The following also fails, this time because `val` goes out of scope and so the
reference to `val` is invalid. I don't know if it is feasible for GCC to detect
this scenario, e.g. the lambda's lifetime extends beyond the scope of
captured-by-reference variables; but, a warning in this case would be nice as
well.

int outer;
auto fn1(int val = 0){
  return [&]{
    outer = val; // invalid
  };
}
std::thread lambda;
void fn2(int val = 0){
  lambda = std::thread([&]{
    outer = val; // invalid
  });
}

The reason I suggest this is because the compilation will succeed without
warning, but the binary can segfault and it is difficult to trace where the
source of the problem is. The first case is more subtle (forgetting `this`),
the second perhaps a bit easier to recognize though when debugging.

Reply via email to