为什么lambda只捕获自动存储变量? [英] Why lambda captures only automatic storage variables?

查看:84
本文介绍了为什么lambda只捕获自动存储变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习C ++中的lambda函数,但我不明白为什么lambda只允许捕获自动存储变量?例如:

I just started learning lambda functions in C++ and i don't understand why lambda's allow capturing only automatic storage variables? For example:

int x;
int main() {
    [&x](int n){x = n;}; // 'x' cannot be captured...
    return 0;
}

另一方面,静态变量根本不需要捕获

On the other hand static variables don't need capturing at all

static int s = 0;
[](int n){s = n;};

那么,为什么不允许第一个示例而第二个可行?

So, why the first example is not allowed and the second works?

推荐答案

您需要回过头来问自己:为什么lambda根本不捕获变量?

You need to go back and ask yourself: Why do lambdas capture variables at all?

Lambda可以使用外部作用域中的变量。但是,如果这些是局部变量,它们将超出范围,并且在函数返回后将无法使用。但是有可能在函数返回后调用lambda(lambda可以从函数返回,或者存储在某些全局变量或实例变量中,等等),并且在函数返回之后,它不能直接引用局部变量,因为它们不再存在。

Lambdas can use variables from an outer scope. However, if those are local variables, they go out of scope and cannot be used after the function returns. But a lambda could potentially be called after the function returns (the lambda could be returned from the function, or stored in some global or instance variable, etc.), and after the function returns, it cannot just refer to the local variables directly, because they no longer exist.

这就是为什么lambda可以通过副本捕获局部变量(在创建lambda时复制它们的值)的原因。 (它们也可以通过引用来捕获,也可以通过复制来捕获。)

That's why lambdas can capture local variables by copy (copy their value at the time the lambda is created). (They can also capture by reference, as an alternative to by copy.)

以上问题仅针对自动存储持续时间的变量存在。对于静态存储持续时间的变量(例如全局变量,静态局部变量),它们在程序的整个生命周期内都有效,并且在任何时间都可以访问它们。

The above issue only exists for variables of automatic storage duration. For variables of static storage duration (e.g. global variables, static local variables), they live for the lifetime of the program, and there is no problem with accessing them at any time.

这篇关于为什么lambda只捕获自动存储变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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