When I use [=] to indicate that I would like all local variables to be captured by value in a lambda, will that result in all local variables in the function being copied, or just all local variables that are used by the lambda?
So, for example, if i I have:
vector<int> my_huge_vector(100000);
int my_measly_int;
some_function([=](int i){ return my_measly_int + i; });
Will my_huge_vector be copied, even though I don’t use it in the lambda?
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_vectoris not captured.Per C++11 §5.1.2[expr.prim.lambda]/11:
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_vectorat all in the body (the "compound statement") of the lambda expression, it is not implicitly captured.To continue with §5.1.2/14
Since your
my_huge_vectoris not implicitly captured and it is not explicitly captured, it is not captured at all, by copy or by reference.