例如:
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.
由于num
既没有声明在任何函数范围内,也没有自动存储期限,因此无法捕获。因此 VS 是对的,g++ 是错的。
关于c++ - lambda 捕获变量的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214623/