Lambda: uncaptured objects in unevaluated context

Viewed 92

I'd appreciate a pointer to the Standard paragraph stating that the following code is well-formed:

int main() {
    int var = 0;
    return [] { return sizeof(var); }(); // var is not captured!
}

Similar example appears e.g. in § 8.4.5.2, but I could not find any verbal description of it.

1 Answers

It's specified in terms of when an entity must be captured, rather than in terms of when it may not.

[expr.prim.lambda.capture] (with some omissions)

8 ... If a lambda-expression or an instantiation of the function call operator template of a generic lambda odr-uses this or a variable with automatic storage duration from its reaching scope, that entity shall be captured by the lambda-expression. ...

[ Example:

void f1(int i) {
  int const N = 20;
  auto m1 = [=]{
    int const M = 30;
    auto m2 = [i]{
      int x[N][M];          // OK: N and M are not odr-used
      // ...
    };
  };
  // ...
}

— end example ]

The key in your code sample is that var is not odr-used, because it is an unevaluated operand. As such, it does not need to be captured.

Related