Taken from an answer to this question, as an example, this is a code that calculates the sum of elements in a std::vector
:
std::for_each(
ve
It's perhaps better to think about a lambda expression as an object that happens to have ()
operator, rather than just a function. The lambda "object" can have fields that remember (or "capture") the out-of-lambda variables at the time of lambda construction, to be used later at the time of lambda execution.
The capture list is simply a declaration of such fields.
(You don't even need to specify the capture list yourself - The [&]
or [=]
syntax instructs the compiler to determine the capture list automatically, based on which variables from the outer scope are used in the lambda body.)
A normal function cannot contain state - it cannot "remember" arguments at one time to be used at another. A lambda can. A manually crafted class with user-implemented ()
operator (aka. "functor") also can, but is far less convenient syntactically.