Lambdas: functions that carry state
Learn
A lambda is an anonymous function you can define inline — but the interesting part is the capture: a lambda can close over variables from its surrounding scope, carrying them along as state. How it captures them (by value or by reference) is the whole game.
int x = 1;
auto byVal = [x]() { return x; }; // copies x now
auto byRef = [&x]() { return x; }; // aliases x Predict the difference capture mode makes.
What does this print? Look closely at how n is captured.
int n = 10;
auto f = [n]() { return n + 1; };
n = 100;
std::cout << f();
Go deeper ↓Lambdas in C++
Once you see that a lambda stores its captures, the question "what is a lambda, really?" has an obvious answer.
Under the hood, what is a C++ lambda expression?
Go deeper ↓Lambdas in C++