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

前端 未结 5 1568
一个人的身影
一个人的身影 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:10

    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.

提交回复
热议问题