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(
vector.begin(),
vector.end(),
[&](int n) {
sum_of_elems += n;
}
);
I understand that lambda functions are just nameless functions.
I understand the lambda functions syntax as explained here.
I do not understand why lambda functions need the capture list, while normal functions do not.
- What extra information does a capture list provide?
- Why do normal functions not need that information?
- Are lambda functions more than just nameless functions?
From the syntax link you gave, the capture list “defines what from the outside of the lambda should be available inside the function body and how”
Ordinary functions can use external data in a few ways:
Lambda add the ability to have one unnamed function within another. The lambda can then use the values you specify. Unlike ordinary functions, this can include local variables from an outer function.
As that answer says, you can also specify how you want to capture. awoodland gives a few exampls in another answer. For instance, you can capture one outer variable by reference (like a reference parameter), and all others by value:
EDIT:
It’s important to distinguish between the signature and what the lambda uses internally. The signature of a lambda is the ordered list of parameter types, plus the type of the returned value.
For instance, a unary function takes a single value of a particular type, and returns a value of another type.
However, internally it can use other values. As a trivial example:
The caller of the lambda only knows that it takes an
intand returns anint. However, internally it happens to use two other variables by value.