Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c++ - In lambda functions syntax, what purpose does a 'capture list' serve?

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.

  1. What extra information does a capture list provide?
  2. Why do normal functions not need that information?
  3. Are lambda functions more than just nameless functions?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. Static fields
  2. Instance fields
  3. Parameters (including reference parameters)
  4. Globals

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:

[=, &epsilon]

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:

[x, y](int z) -> int 
{
   return x + y - z;
}

The caller of the lambda only knows that it takes an int and returns an int. However, internally it happens to use two other variables by value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...