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); } 
5
  • 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. Commented May 9, 2018 at 7: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. Commented May 9, 2018 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! Commented May 9, 2018 at 13:46
  • There are a couple of interesting cases wrt to constexpr, see Understanding the example on lvalue-to-rvalue conversion Commented May 17, 2018 at 13:06
  • 1
    This would also work for constant integral but not const floating point Commented May 17, 2018 at 13:12

1 Answer 1

33

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.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.