更新时间:2023-11-11 12:57:58
我相信 VS2010 这次是正确的,我会检查我是否有方便的标准,但目前我没有.
I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
现在,就像错误消息所说的那样:您无法捕获 lambda 封闭范围之外的内容.†grid
不在封闭范围内,但是 this
是(在成员函数中,对 grid
的每次访问实际上都是作为 this->grid
发生的).对于您的用例,捕获 this
有效,因为您将立即使用它并且您不想复制 grid
Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda.†grid
is not in the enclosing scope, but this
is (every access to grid
actually happens as this->grid
in member functions). For your usecase, capturing this
works, since you'll use it right away and you don't want to copy the grid
auto lambda = [this](){ std::cout << grid[0][0] << "
"; }
但是,如果您想要存储网格并复制它以供以后访问,而您的 puzzle
对象可能已经被销毁,则您需要制作一个中间的本地副本:
If however, you want to store the grid and copy it for later access, where your puzzle
object might already be destroyed, you'll need to make an intermediate, local copy:
vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy
† 我正在简化 - 谷歌搜索达到范围"或参阅第 5.1.2 节了解所有血腥细节.
† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.