33
votes

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);
}
1
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
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
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
There are a couple of interesting cases wrt to constexpr, see Understanding the example on lvalue-to-rvalue conversion - Shafik Yaghmour

1 Answers

32
votes

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.