λ捕获变量的规则 [英] Rule for lambda capture variable

查看:146
本文介绍了λ捕获变量的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

  class示例
{
public:
explicit int n):num(n){}
void addAndPrint(vector< int>& v)const
{
for_each(v.begin(),v.end() num](int n){cout<< num + n<
}
private:
int num;
};

int main()
{
vector< int> v = {0,1,2,3,4};

示例ex(1);
ex.addAndPrint(v);
return 0;
}



当您在MSVC2010中编译和运行此错误时,会出现以下错误: p>

错误C3480:'Example :: num':lambda捕获变量必须来自包含函数范围



但是,使用g ++ 4.6.2(prerelease),你会得到:



1 2 3 4 5

根据标准草案,哪个编译器是正确的?

解决方案

9:


本地lambda表达式的到达范围是
的集合,包含范围,直到并包括最内层函数
及其参数。


和5.1.2 / 10:


使用通常的规则
查找捕获列表中的标识符,用于非限定名称查找(3.4.1);每个这样的查找将找到具有在局部lambda表达式的到达
范围中声明的自动存储持续时间的
变量。


由于 num 既不在任何函数作用域中声明,也不具有自动存储持续时间,因此无法捕获。因此VS是正确的,g ++是错误的。


For example:

class Example
{
public:
    explicit Example(int n) : num(n) {}
    void addAndPrint(vector<int>& v) const
    {
        for_each(v.begin(), v.end(), [num](int n) { cout << num + n << " "; });
    }
private:
    int num;
};

int main()
{
    vector<int> v = { 0, 1, 2, 3, 4 };

    Example ex(1);
    ex.addAndPrint(v);
    return 0;
}

When you compile and run this in MSVC2010 you get the following error:

error C3480: 'Example::num': a lambda capture variable must be from an enclosing function scope

However, with g++ 4.6.2 (prerelease) you get:

1 2 3 4 5

Which compiler is right according to the standard draft?

解决方案

5.1.2/9:

The reaching scope of a local lambda expression is the set of enclosing scopes up to and including the innermost enclosing function and its parameters.

and 5.1.2/10:

The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

As num is neither declared in any function scope nor has automatic storage duration, it cannot be captured. Thus VS is right and g++ is wrong.

这篇关于λ捕获变量的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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