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

前端 未结 5 1546
一个人的身影
一个人的身影 2020-12-24 04:00

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         


        
5条回答
  •  醉梦人生
    2020-12-24 04:12

    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.

提交回复
热议问题