Igor
Igor

Reputation: 1059

C++ lambda capture result

For example I have next code:

int func() 
{
    int i = 0;
    int j = 0;
    auto lambda{[&](){ return i; }};
    return lambda();
}

Will be j captured also by reference or lambda captures only objects that it uses?

Upvotes: 1

Views: 85

Answers (2)

khuttun
khuttun

Reputation: 733

No, j will not be captured.

From https://en.cppreference.com/w/cpp/language/lambda:

The captures is a comma-separated list of zero or more captures, optionally beginning with the capture-default. The only capture defaults are

  • & (implicitly capture the used automatic variables by reference) and
  • = (implicitly capture the used automatic variables by copy).

Upvotes: 4

acraig5075
acraig5075

Reputation: 10756

No, j won't be captured

From Lambda capture docs:

& (implicitly capture the used automatic variables by reference)

Note the word "used"

Upvotes: 6

Related Questions