Rule for lambda capture variable

落爺英雄遲暮 提交于 2019-12-21 02:20:35

问题


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?


回答1:


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.




回答2:


Standard says the following (5.1.2):

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.

To my understanding GCC compiler is right because 'num' is in the reaching scope at the point of lambda declaration.



来源:https://stackoverflow.com/questions/7214623/rule-for-lambda-capture-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!