Really? Should gcc 4.7.0 be saying "number was not declared in this scope"? Are lambda's only allowed to see what's in scope where they are defined rather than where they are called?
This is a simple test case, it would be easy to define number before defining func. But sometimes, that's not possible, as shown below.
If so, I know the solution is to use a parameter rather than a capture, I'm just surprised at this.
1 2 3 4 5
int main() {
auto func = [&] { ++number; };
unsignedlong number = 0; // moving this up one line makes this code compile
func();
}
#include <iostream>
#include <vector>
usingnamespace std;
int main() {
vector<unsignedlong> theVec = {1, 4, 8, 10};
vector<unsignedlong> theOtherVec = {3, 5, 8};
unsignedlong thisWorks = 5;
auto func = [&] {
cout << thisWorks << endl;
cout << thisDoesnt << endl;
};
for(unsignedlong& thisDoesnt : theVec {
func();
}
for(unsignedlong& thisDoesnt : theOtherVec {
func();
}
func(); // this of course has to error out
}
I guess this could make some sense, since func could be called where thisDoesnt exists, or where it doesn't exist, but I am surprised the compiler can't sort that out and only complain where necessary.
Lambdas are syntactic sugar for automatic generation of functor types, not magical objects capable of breaking the rules of static typing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class lambda{
unsignedlong &number;
public:
lambda(unsignedlong &n):number(n){}
voidoperator()(){
++number;
}
};
int main() {
lambda func(number);
unsignedlong number = 0; // moving this up one line makes this code compile
func();
}