Lance LI
Lance LI

Reputation: 113

Why can I capture an undeclared variable in mutable lambda in C++

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; 
    }();
}

Upvotes: 2

Views: 281

Answers (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();
}

Upvotes: 1

Related Questions