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
Are lambda functions more than just nameless functions?
YES! Apart from being nameless, they can refer to the variables in the lexically enclosed scope. In your case, an example would be the sum_of_elems
variable (its neither a parameter nor a global variable I suppose). Normal functions in C++ can't do that.
What extra information does a capture list provide?
The capture list provides the
In other (eg. functional) languages, this isn't necessary, because they always refer to values in one fashion (eg. if values are immutable, the capture would be by value; other possibility is that everything is a variable on the heap so everything is captured by refrence and you needn't worry about its lifetime etc.). In C++, you have to specify it to choose between reference (can change the variable outside, but will blow up when the lambda outlives the variable) and value (all changes isolated inside the lambda, but will live as long as the lambda - basically, it will be a field in a structure representing the lambda).
You can make the compiler to capture all the needed variables by using the capture-default symbol, which just specifies the default capture mode (in your case: &
=> reference; =
would be value). In that case, basically all variables referenced in the lambda from the outer scope are captured.