我创建了一个简单的lambda,如下所示,它按预期工作(GCC 4.6.4和4.7.2 - 演示).但后来我检查了标准和5.1.2-8明确禁止使用=和thislambda捕获.
...如果lambda-capture包含一个捕获默认值为=,则lambda-capture不应包含此值,并且它包含的每个标识符都应以&开头....
我读错了,这实际上是允许的(虽然这个例子肯定表明这是禁止的)?如果不是,那么我很难理解为什么不允许这样做.而且,这是否意味着GCC允许它是错误的?
#include <iostream>
#include <functional>
using namespace std;
struct sample {
int a;
std::function<int()> get_simple(int o) {
return [=,this]() {
return a + o;
};
}
};
int main() {
sample s;
auto f = s.get_simple(5);
s.a = 10;
cout << f() << endl; //prints 15 as expected
}
Run Code Online (Sandbox Code Playgroud)
如果您已经通过设置[=]指定了默认捕获模式,则不需要捕获"this"字段.请参阅下文,我明确传递"this"和o by value.因此,警告告诉您在这种情况下您正在冗余地传递"this",因为在指定=或&作为默认捕获模式时,您会自动获得"this".因此,在未指定默认捕获模式时,仅指定"this".见下文.
#include <iostream>
#include <functional>
using namespace std;
struct sample {
int a;
std::function<int()> get_simple(int o)
{
return [o,this]{ return a + o; };
}
};
int main() {
sample s;
auto f = s.get_simple(5);
s.a = 10;
cout << f() << endl; //prints 15 as expected
}
Run Code Online (Sandbox Code Playgroud)