Access to constexpr variable inside lambda expression without capturing

  • A+
Category:Languages

In the following example, I can access the constexpr variable x from inside the lambda y without explicitly capturing it. This is not possible if x is not declared as constexpr.

Are there special rules that apply to constexpr for capturing?

int foo(auto l) {     constexpr auto x = l(); // OK //    auto x = l();         // NOK     auto y = []{return x;};     return y(); }  auto l2 = []{return 3;};  int main() {     foo(l2); } 


Are there special rules that apply to constexpr for capturing/accessing?

Yes, constexpr variables could be read without capturing in lambda:

A lambda expression can read the value of a variable without capturing it if the variable

  • has const non-volatile integral or enumeration type and has been initialized with a constant expression, or
  • is constexpr and trivially copy constructible.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: