在成员函数内的lambda捕获列表中使用数据成员

Using data member in lambda capture list inside a member function

本文关键字:列表 数据成员 函数 成员 lambda      更新时间:2023-10-16

下面的代码可以在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;
    });
}

错误:

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中的数据成员?

备选方案概要:

capture this:

auto lambda = [this](){};

使用成员的本地引用:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

c++ 14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

示例:https://godbolt.org/g/dEKVGD

我相信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

†我正在简化-谷歌"达到范围"或见§5.1.2所有血腥的细节。

我认为,您需要捕获this

限制lambda的作用域而不是让它访问整个this的另一种方法是传递对成员变量的局部引用,例如

auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
            i++;
            cout<<i<<endl;
   });