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?
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.
5.1.2/9:
and 5.1.2/10:
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.