Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do c++11 lambdas capture variables they don't use?

Tags:

c++

c++11

lambda

People also ask

How do you capture variables in lambda?

Capture clause A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.

Does lambda capture reference by value?

Lambdas always capture objects, and they can do so by value or by reference.

How does lambda capture work?

By default, variables are captured by const value . This means when the lambda is created, the lambda captures a constant copy of the outer scope variable, which means that the lambda is not allowed to modify them. In the following example, we capture the variable ammo and try to decrement it.

Can lambda function access local variables?

Local variables from outer scope can be captured inside Lambda in 2 modes i.e.


Each variable expressly named in the capture list is captured. The default capture will only capture variables that are both (a) not expressly named in the capture list and (b) used in the body of the lambda expression. If a variable is not expressly named and you don't use the variable in the lambda expression, then the variable is not captured. In your example, my_huge_vector is not captured.

Per C++11 §5.1.2[expr.prim.lambda]/11:

If a lambda-expression has an associated capture-default and its compound-statement odr-uses this or 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.

Your lambda expression has an associated capture default: by default, you capture variables by value using the [=].

If and only if a variable is used (in the One Definition Rule sense of the term "used") is a variable implicitly captured. Since you don't use my_huge_vector at all in the body (the "compound statement") of the lambda expression, it is not implicitly captured.

To continue with §5.1.2/14

An entity is captured by copy if

  • it is implicitly captured and the capture-default is = or if
  • it is explicitly captured with a capture that does not include an &.

Since your my_huge_vector is not implicitly captured and it is not explicitly captured, it is not captured at all, by copy or by reference.


No, my_huge_vector will not be captured. [=] means all used variables are captured in the lambda.