問題描述
以下代碼使用 gcc 4.5.1 編譯但不適用于 VS2010 SP1:
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;
}
這是錯誤:
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> 哪個編譯器是對的?
1> which compiler is right?
2> 如何在 VS2010 的 lambda 中使用成員變量?
2> How can I use member variables inside a lambda in VS2010?
推薦答案
我相信 VS2010 這次是正確的,我會檢查我是否有方便的標(biāo)準(zhǔn),但目前我沒有.
I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
現(xiàn)在,就像錯誤消息所說的那樣:您無法捕獲 lambda 封閉范圍之外的內(nèi)容.? grid
不在封閉范圍內(nèi),但是 this
是(在成員函數(shù)中,對 grid
的每次訪問實際上都是作為 this->grid
發(fā)生的).對于您的用例,捕獲 this
有效,因為您將立即使用它并且您不想復(fù)制 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] << "
"; }
但是,如果您想要存儲網(wǎng)格并復(fù)制它以供以后訪問,而您的 puzzle
對象可能已經(jīng)被銷毀,則您需要制作一個中間的本地副本:
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 節(jié)了解所有血腥細節(jié).
? I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.
這篇關(guān)于在成員函數(shù)內(nèi)的 lambda 捕獲列表中使用成員變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!