我创建了一个简单的 lambda,如下所示,它按预期工作(GCC 4.6.4 和 4.7.2 -- demo)。但后来我检查了标准,5.1.2-8 明确禁止在 lambda 捕获中使用 =
和 this
。
... If a lambda-capture includes a capture-default that is =, the lambda-capture shall not contain this and each identifier it contains shall be preceded by &. ...
我是不是读错了什么,这实际上是允许的(尽管这个例子明确表明这是被禁止的)?如果不是,那么我无法理解为什么不允许这样做。而且,这是否意味着 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
}
最佳答案
如果您已经通过设置 [=] 指定了默认捕获模式,则无需捕获“this”字段。请参阅下面我明确按值传递“this”和 o 的地方。因此,警告告诉您在这种情况下您多余地传递了“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
}
关于c++ - 为什么带有 = 的 lambda 是不允许的(但 GCC 接受),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17872224/