c – lambda捕获变量的规则

前端之家收集整理的这篇文章主要介绍了c – lambda捕获变量的规则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例如:
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;
}

当您在MSVC2010中编译并运行它时,您会收到以下错误

错误C3480:’Example :: num’:lambda捕获变量必须来自封闭的函数作用域

但是,使用g 4.6.2(预发行版),您将得到:

1 2 3 4 5

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

解决方法

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.

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

由于num既未在任何函数范围内声明,也未具有自动存储持续时间,因此无法捕获它.因此VS是对的,g是错的.

原文链接:https://www.f2er.com/c/118539.html

猜你在找的C&C++相关文章