在成员函数中的lambda捕获列表中使用成员变量 [英] Using member variable in lambda capture list inside a member function
问题描述
以下代码使用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>>格;
map< int,set< int>>组;
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;
}
这是错误:
错误C3480:'puzzle :: grid':lambda捕获变量必须来自包含函数范围
警告C4573:'puzzle :: grid'需要编译器捕获this,但当前的默认捕获模式不允许它
/ p>
1>哪个编译器是正确的?
2>如何在VS2010中的lambda中使用成员变量?
我相信VS2010这次是正确的,我会检查我是否有标准的方便, 't。
现在,它就像错误消息所说:你不能捕获lambda的封闭范围之外的东西。† 不在封闭范围内,但
此
是(每次访问 grid
实际上发生在成员函数中的 this-> grid
)。对于你的usecase,捕获这
工程,因为你马上就会使用它,你不想复制网格
auto lambda = [this](){std :: cout< grid [0] [0]< \\\
; }
然而,如果您想存储网格并将其复制以供稍后访问, c $ c> puzzle 对象可能已被销毁,您需要创建一个中间本地副本:
vector< vector< int> > tmp(grid);
auto lambda = [tmp](){}; //捕获每个副本的本地副本
'简化 - Google for达到范围或参见§5.1.2了解所有的血腥细节。
The following code compiles with gcc 4.5.1 but not with 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;
}
This is the error:
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
So,
1> which compiler is right?
2> How can I use member variables inside a lambda in VS2010?
I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
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] << "\n"; }
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
† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.
这篇关于在成员函数中的lambda捕获列表中使用成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!