2

I created a simple lambda as below and it works as expected (GCC 4.6.4 and 4.7.2 -- demo). But then I checked the standard and 5.1.2-8 explicitly forbids using an = and this in the lambda captures.

... 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 &. ...

Am I reading something wrong and this is actually allowed (though the example definitely shows this as forbidden)? If no, then I'm having trouble understanding why it isn't allowed. And also, does that mean GCC is wrong to allow it?

#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
}
4

3 回答 3

5

如果您已经通过设置 [=] 指定了默认捕获模式,则不需要捕获“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
}
于 2013-07-26T03:46:08.640 回答
3

使用在 GCC 4.8.1 中编译的代码并使用-Wall标志,编译会发出以下警告:

main.cpp:在成员函数'std::function sample::get_simple(int)'中:

main.cpp:10:19:警告:“this”的显式复制捕获与默认复制捕获冗余[默认启用]

     return [=,this]() {
               ^

我认为这是由 GCC 制作的,与 C++11 之前的标准 lambda 兼容。

于 2013-07-26T03:12:25.483 回答
1

现在P0409R2允许这样做。

此外,隐式thisin[=]已被P0806R2弃用。例如,尝试 Clang++ 8 -std=c++2a,您将收到警告 [-Wdeprecated-this-capture] for [=].

于 2019-08-01T11:10:44.343 回答