在 lambda 函数语法中,“捕获列表"有什么用途? [英] In lambda functions syntax, what purpose does a 'capture list' serve?

查看:30
本文介绍了在 lambda 函数语法中,“捕获列表"有什么用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取自对这个问题的回答,例如,这个是计算 std::vector:

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;
    }
);

我明白 lambda 函数只是无名函数.

I understand that lambda functions are just nameless functions.

我了解 lambda 函数语法如此处所述.

I understand the lambda functions syntax as explained here.

我不明白为什么 lambda 函数需要捕获列表,而普通函数不需要.

I do not understand why lambda functions need the capture list, while normal functions do not.

  1. 捕获列表提供哪些额外信息?
  2. 为什么普通函数不需要这些信息?
  3. lambda 函数不仅仅是无名函数吗?

推荐答案

根据您提供的语法链接,捕获列表定义了 lambda 外部的哪些内容应在函数体内可用以及如何使用"

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. 静态字段
  2. 实例字段
  3. 参数(包括参考参数)
  4. 全局变量

Lambda 添加了将一个未命名函数包含在另一个函数中的功能.然后 lambda 可以使用您指定的值.与普通函数不同,这可以包含来自外部函数的局部变量.

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.

正如那个答案所说,您还可以指定您想要的捕获方式.awoodland 在另一个答案中给出了一些示例.例如,您可以通过引用(如引用参数)捕获一个外部变量,并通过值捕获所有其他变量:

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]

区分签名和 lambda 内部使用的内容很重要.lambda 的签名是参数类型的有序列表,加上返回值的类型.

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;
}

lambda 的调用者只知道它接受一个 int 并返回一个 int.然而,在内部它碰巧按值使用了另外两个变量.

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.

这篇关于在 lambda 函数语法中,“捕获列表"有什么用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆