以下代码使用gcc 4.5.1编译,但不能使用VS2010 SP1编译:
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <set>
#include <algorithm>
using namespace std;
class puzzle
{
vector<vector<int>> grid;
map<int,set<int>> groups;
public:
int member_function();
};
int puzzle::member_function()
{
int i;
for_each(groups.cbegin(),groups.cend(),[grid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
}
int main()
{
return 0;
}
这是错误:
error C3480: 'puzzle::grid': a lambda capture variable must be from an enclosing function scope
warning C4573: the usage of 'puzzle::grid' requires the compiler to capture 'this' but the current default capture mode does not allow it
所以,
1>哪个编译器正确?
2>如何在VS2010的lambda中使用成员变量?
我相信VS2010这次是对的,我会检查我是否有标准的方便工具,但是目前我没有。
现在,就像错误消息中所说的一样:您无法在lambda的封闭范围之外捕获东西。† grid
不在封闭范围内,而是this
(grid
实际上每次访问都像this->grid
在成员函数中一样)。对于您的用例来说,捕获this
是可行的,因为您将立即使用它,并且您不想复制grid
auto lambda = [this](){ std::cout << grid[0][0] << "\n"; }
但是,如果您想存储网格并复制它以供以后访问(您的puzzle
对象可能已经被销毁),则需要制作一个中间的本地副本:
vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy
†我正在简化-Google适用于“扩展范围”,或者请参阅§5.1.2了解所有细节。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句