Lambda: scope where defined, rather than where called?

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; };
   unsigned long number = 0; // moving this up one line makes this code compile
   func();
}




Longer example...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<unsigned long> theVec = {1, 4, 8, 10};
   vector<unsigned long> theOtherVec = {3, 5, 8};

   unsigned long thisWorks = 5;
   auto func = [&] {
      cout << thisWorks << endl;
      cout << thisDoesnt << endl;
   };

   for(unsigned long& thisDoesnt : theVec {
      func();
   }

   for(unsigned long& 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.
What if the lambda is being supplied as a function argument and the call site isn't in the current function?

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{
    unsigned long &number;
public:
    lambda(unsigned long &n):number(n){}
    void operator()(){
        ++number;
    }
};

int main() {
   lambda func(number);
   unsigned long number = 0; // moving this up one line makes this code compile
   func();
}
Last edited on
Topic archived. No new replies allowed.