根据此问题的答案和注释,当通过值捕获引用变量时,lambda对象应该复制引用的对象,而不是引用本身.但是,海湾合作委员会似乎并没有这样做.
使用以下测试:
#include <stddef.h>
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char** argv)
{
int i = 10;
int& ir = i;
[=]
{
cout << "value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
[&]
{
cout << "reference capture" << endl
<< "i: " << i << endl …Run Code Online (Sandbox Code Playgroud) 我在std::for_each类的成员函数的局部变量上使用循环.我想从for_each中的lambda调用同一个类的另一个成员函数.以下是我正在尝试做的简化示例:
void some_class::another_function()
{
cout << "error";
}
void some_class::some_function( function<bool(const int)> &f)
{
vector<int> local_variable = {0,0,0,1,1,3,5,43};
std::for_each( local_variable.begin(), local_variable.end(),
[&f](const int item)
{
if( !f(item) )
another_function();
}
}
Run Code Online (Sandbox Code Playgroud)
GCC 4.6告诉我this没有捕获(所以我应该这样做).这是最好的解决方案吗?或者我应该只捕获我需要的那些功能(但对于较大的构造可能会很麻烦)?