Why lambda captures only automatic storage variables?

喜欢而已 提交于 2020-08-22 08:29:07

问题


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?


回答1:


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

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.

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.




回答2:


You need to change scope. Look at this:

int x = 4;

int main()
{
    cout << "::x = " << ::x << endl;

    [&](int a){ ::x = a; }(2);

    cout << "::x = " << ::x << endl;

    return 0;
}

Output:

::x = 4
::x = 2


来源:https://stackoverflow.com/questions/24474957/why-lambda-captures-only-automatic-storage-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!