c++ - 在成员函数内的 lambda 捕获列表中使用成员变量

标签 c++ visual-studio-2010 lambda c++11

以下代码使用 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

† 我正在简化 - 谷歌“达到范围”或查看 §5.1.2 了解所有血腥细节。

关于c++ - 在成员函数内的 lambda 捕获列表中使用成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895879/

相关文章:

c++ - 使用对 vector 的 vector ?

c++ - Arduino清除缓冲区

wpf - WPF ComboBox 中的 DataTextField 和 DataValueField?

visual-studio-2010 - 尝试连接到 Visual Studio 2010 中的数据库时出现意外错误

java - UncheckedIOException 和 Stream API 的习语/最佳实践是什么?

c++ - 如何在 C++ 中从宏组成变量名?

c++ - 如何手动使另一个控件发出信号?

wpf - 如何在不安装 Visual Studio 的情况下安装 Microsoft® Surface® 2.0 SDK

C++ 类变量 std::function 具有默认功能并且可以更改

c# - 从 lambda 查询的结果访问关联时出现问题