do c ++ 11 lambdas捕获他们不使用的变量? [英] Do c++11 lambdas capture variables they don't use?

查看:167
本文介绍了do c ++ 11 lambdas捕获他们不使用的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 [=] 来表示我想要所有的局部变量被一个lambda捕获的值,将导致 all <



所使用的所有局部变量因此,例如,如果我有:

 矢量< int> my_huge_vector(100000); 
int my_measly_int;
some_function([=](int i){return my_measly_int + i;});将$ my_huge_vector复制,即使我不在lambda中使用它吗?

将会复制


$ b <

解决方案

捕获捕获列表中明确命名的每个变量。默认捕获将仅捕获(a)在捕获列表中未明确命名的变量,和(b)在lambda表达式主体中使用的变量 。如果未明确命名变量,并且不在lambda表达式中使用该变量,那么不会捕获该变量。在您的示例中,未捕获 my_huge_vector



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


如果一个lambda表达式具有关联的 capture-default 以及其复合语句 odr-使用 this > odr-used 实体未被显式捕获,则说明 odr使用的实体被隐式捕获。


您的lambda表达式具有关联的捕获默认值:默认情况下,您使用 [=] 按值捕获变量。



当且仅当使用变量时(在术语used的单一定义规则意义上)是隐式捕获的变量。因为在lambda表达式的主体(复合语句)中根本不使用 my_huge_vector ,它不会被隐式捕获。



继续使用§5.1.2/ 14





  • 它被隐式捕获,并且捕获默认 = 如果

  • 使用不包含& 的捕获显式捕获。


由于您的 my_huge_vector 捕获并且没有被显式捕获,根本没有被拷贝或通过引用捕获。


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_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.

这篇关于do c ++ 11 lambdas捕获他们不使用的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆