例如:
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; }
当您在MSVC2010中编译并运行它时,您会收到以下错误:
错误C3480:’Example :: num’:lambda捕获变量必须来自封闭的函数作用域
但是,使用g 4.6.2(预发行版),您将得到:
1 2 3 4 5
根据标准草案,哪个编译器是正确的?
解决方法
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.
和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.