意味着所有的局部变量都将被复制吗

意味着所有的局部变量都将被复制吗

本文介绍了[=]意味着所有的局部变量都将被复制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用 [=] 写一个lambda时,是否意味着所有的局部变量都将被复制到创建的结构体的成员,或者我可以假设只有那些将实际使用在lambda?例如:

  void f()
{
vector< int& v(10000);
const int n = 5;
const int DivByNCnt = count_if(istream_iterator (cin),istream_iterator< int>(),
[=](int i)
{
return i%n = = 0;
});以下哪一项(如果有)是真的?




$ b

b
$ b

  • n和v都将被复制

  • n将被复制,v不会被复制

  • n将被复制,v可能会也可能不会被复制,具体取决于植入/优化设置。



参数的缘故,矢量的副本构造函数有副作用。

解决方案

否。它只是意味着环境范围内的所有局部变量都可以在lambda体内查找。只有如果指向一个环境局部变量的名称,那个变量将被捕获,并且它将被捕获。



捕获任何东西shorthands = & 只是语法糖,实际上告诉编译器我的意思是。






来自5.1.2 / 11-12的正式参考:

请注意, capture-default 是指 [=] [&] 。要重复,指定捕获默认值不捕获任何内容;只有odr使用一个变量。


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?

  • both 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 implmenentation/optimization settings.

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:

Note that "capture-default" refers to [=] and [&]. To repeat, specifying a capture-default doesn't capture anything; only odr-using a variable does.

这篇关于[=]意味着所有的局部变量都将被复制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 02:32