Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rule for lambda capture variable

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?

like image 689
Jesse Good Avatar asked Aug 27 '11 12:08

Jesse Good


1 Answers

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.

like image 99
n. 1.8e9-where's-my-share m. Avatar answered Oct 24 '22 03:10

n. 1.8e9-where's-my-share m.