Does [=] have all local variables copied?

When I write lambda with [=] , does this mean that all my local variables will be copied to the members of the created structure, or can I assume that only those that are really used in 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?

  • and n and v will be copied
  • n will be copied, v will not
  • n will be copied, v may or may not be copied depending on the implantation / optimization settings.

Suppose for an argument that a vector copy constructor has side effects.

+61
c ++ lambda c ++ 11 capture
Mar 25 '13 at 10:19
source share
2 answers

No. It just means that all local variables from scope are searchable inside the lambda body. Only if you refer to the name of a local local variable will this variable be captured and fixed by value.

"Remove something" abbreviates = and & is just syntactic sugar, essentially telling the compiler to "find out what I mean."




Formal link from 5.1.2 / 11-12:

If a lambda expression has a default capture-related function, and its compound operator odr uses [...] a variable with automatic storage duration, and an object using odr is not explicitly captured, then an object using odr is called implicit capture [.. .]

An object is captured if it is latched explicitly or implicitly.

Note that "capture-default" refers to [=] and [&] . Repeat, indicating capture default, does not fix anything; only the odr-using variable is used.

+63
Mar 25 '13 at 10:22
source share

No! (Luckily)

You can program your code to check if your compiler really does (or not). For example, gcc 4.8.0 meets the requirements.




In accordance with what the Standard actually provides (addresses back):

Β§5.1.2 / 14 An entity is captured by a copy if it is implicitly captured, and the default is = or if it is explicitly captured with a capture that does not include & . For each object captured by the copy, an unnamed non-static data member is declared in the close type.

$ 5.1.2 / 11 If a lambda expression has a default capture and its compound operator odr-uses (3.2) this or a variable with automatic storage duration, and an object using odr is not explicitly captured, then an object using odr is called implicit capture; such objects must be declared within the scope of the lambda expression.

Β§5.1.2 / 9 A lambda expression, the smallest enclosing area of ​​which is the block region (3.3.3), is a local lambda expression; any other lambda expression should not have a capture list in its lambda introducer. The scope for reaching a local lambda expression is a set of encompassing action areas up to the innermost encompassing function and its parameters. [Note. This scope includes any intermediate lambda expressions. -end note]

+22
Mar 25 '13 at 10:26
source share



All Articles