2

We know that in C++, lambda expressions can capture local variables either by-copy (value) or by-reference, but why can I capture a variable which is not declared anywhere (not in enclosing scope)? How do standards define this behavior and what's the motivation behind this choice?

#include <iostream>
using namespace std;
int main()
{
    [pi=3.14]() mutable { 
       pi = 3.1415926; 
       cout << pi << endl; 
    }();
}
ILikeTurtles
  • 1,012
  • 4
  • 16
  • 47
Lance LI
  • 113
  • 3
  • 9
  • I think you discovered generalized lambda capture: https://stackoverflow.com/a/20669290/6608866 – PaulR May 30 '18 at 15:16

1 Answers1

1

When lambdas were first introduced in C++11, you could only capture existing variables in them. However, this was broadened in later iterations of the standard and you can now define members for the closure type without necessarily capturing a variable. That is exactly what you're doing in your example.

Perhaps more common use for this "capture an expression" functionality is to enable capturing move-only types by value:

std::unique_ptr<Foo> foo = whatever();
[p = std::move(foo)]() {
  p->bar();
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455