c++ - 为什么带有 = 的 lambda 是不允许的(但 GCC 接受)

标签 c++ gcc c++11

我创建了一个简单的 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/

相关文章:

c++ - 在 C++ 中使用 bitset 容器

c++ - __gxx_personality_v0 有什么用?

c - 我怎样才能让 GCC 用 SSE 指令向量化这个简单的复制循环?

c++ - 编写编译器 : how to get simple templates to work?

c++ - 不透明指针 (pimpl) 以及信号和槽

c++ - 从 cin 中存储 '\n' 字符

c++ - GMP 内存管理功能的 Clang 错误

c++ - string::c_str() 在 C++11 中不再以 null 终止吗?

c++ - 作为成员变量的 lambda 函数崩溃

类似于eternity的C++对象持久化库