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 it in MSVC2010, you get the following error:

error C3480: 'Example :: num': lambda capture variable must be from the application area

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

1 2 3 4 5

Which compiler is right according to the standard draft?

+7
source share
2 answers

5.1.2 / 9:

The achieved volume of the local lambda expression is a set of spanning areas of action up to the innermost spanning function and its parameters.

and 5.1.2 / 10:

Identifiers in the capture list are scanned by the usual rules for finding an unqualified name (3.4.1); each such search will find a variable with automatic storage time declared in reaching the local lambda expression region.

Since num not declared in any area of ​​the function, nor in the state of automatic storage, it cannot be captured. So VS is right, and g ++ is wrong.

+7
source

The standard says the following (5.1.2):

Identifiers in the capture list are scanned using the usual rules for finding unqualified names (3.4.1); each such search should find a variable with automatic storage time declared in the scope of the local lambda expression.

As far as I understand, the GCC compiler is right because 'num' is in scope at the lambda declaration point.

0
source

All Articles