When I write a lambda with [=]
, does it mean that all my local variables will be copied into members of the created struct or can I assume that only those will that are actually used in the lambda? For example:
void f() { vector<int> v(10000); const int n = 5; const int DivByNCnt = count_if(istream_iterator<int>(cin), istream_iterator<int>(), [=](int i) { return i % n == 0; }); }
Which of the following, if any, is true?
Suppose for the argument's sake that vector's copy constructor has side effects.
No. It just means that all local variables from the ambient scope are available for lookup inside the body of the lambda. Only if you refer to a name of an ambient local variable will that variable be captured, and it'll be captured by value.
The "capture anything" shorthands =
and &
are just syntactic sugar, essentially, telling the compiler to "figure out what I mean".
A formal reference from 5.1.2/11-12:
If a lambda-expression has an associated capture-default and its compound-statement odr-uses [...] a variable with automatic storage duration and the odr-used entity is not explicitly captured, then the odr-used entity is said to be implicitly captured [...]
An entity is captured if it is captured explicitly or implicitly.
Note that "capture-default" refers to [=]
and [&]
. To repeat, specifying a capture-default doesn't capture anything; only odr-using a variable does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With