34

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) {
    // OK
    constexpr auto x = l();
    auto y = []{return x;};
    return y();

    // NOK
    // auto x2 = l();
    // auto y2 = []{ return x2; };
    // return y2();        
}

auto l2 = []{return 3;};

int main() {
    foo(l2);
}
Barry
  • 286,269
  • 29
  • 621
  • 977
wimalopaan
  • 4,838
  • 1
  • 21
  • 39
  • 6
    Fascinated to know why the down-vote. This looks an intriguing corner of the standard to me, and a few minutes googling didn't find the answer. – Martin Bonner supports Monica May 09 '18 at 07:06
  • I edited the question because it took me quite some time reading the question to understand why the non-constexpr declaration of `x` was marked `NOK`, and I didn't understand until I read the answer. Hopefully this makes it clearer. If you disagree, feel free to roll back. – Barry May 09 '18 at 13:09
  • Sometimes it is hard to ask a question in a straightforward way, if you don't know the anser yet. Thank you for clearifying the question! – wimalopaan May 09 '18 at 13:46
  • There are a couple of interesting cases wrt to constexpr, see [Understanding the example on lvalue-to-rvalue conversion](https://stackoverflow.com/q/28506342/1708801) – Shafik Yaghmour May 17 '18 at 13:06
  • 1
    This would also work for [constant integral but not const floating point](https://stackoverflow.com/q/34323489/1708801) – Shafik Yaghmour May 17 '18 at 13:12

1 Answers1

32

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.
songyuanyao
  • 169,198
  • 16
  • 310
  • 405