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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With