Tracer
Tracer

Reputation: 2736

Why lambda captures only automatic storage variables?

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?

Upvotes: 25

Views: 20462

Answers (2)

newacct
newacct

Reputation: 122489

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.

Upvotes: 31

Dakorn
Dakorn

Reputation: 903

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

Upvotes: 19

Related Questions