繁体   English   中英

C++11 lambda 捕获`this`并按值捕获局部变量

[英]C++11 lambda capture `this` and capture local variables by value

下面的 lambda 函数捕获了this (所以bar()可以访问它的实例变量)和局部变量a,b,c

class Foo {
  int x, y, z;
  std::function<void(void)> _func;
  // ...
  void bar() {
     int a,b,c;
     // ...
     _func = [this,a,b,c]() { // lambda func
        int u = this->x + a;
        // ...
     };
  }
};

但是,如果我想捕捉许多实例变量,并希望避免明确的捕获列表命名它们,我似乎并没有能够做到这一点:

     _func = [this,=]() { // lambda func
        // ...
     };

我在下面的=处收到编译器错误this,

  error: expected variable name or 'this' in lambda capture list 

如果我试试这个

     _func = [=,this]() { // lambda func
        // ...
     };

我得到

  error: 'this' cannot be explicitly captured when the capture default is '='

是否有按值捕获this和其他所有内容的简写?

更新: [=, this]作为 lambda 捕获是C++20 的一个新特性

正如 cppreference 所说:

[=] 通过复制捕获 lambda 主体中使用的所有自动变量,如果存在则通过引用捕获当前对象

[=]你想要做什么-它抓住了什么不是值的成员变量,而*this引用(或this按值)。

[*this,=]按值捕获局部变量对象。

[&]通过引用捕获局部变量,通过引用捕获*this或通过值捕获this (指针)。

这两个默认拍摄模式拍摄this相同的方式。 只有在中你才能改变它。

[=]已经按值捕获了this 在这里查看以下代码: http : //cpp.sh/87iw6

#include <iostream>
#include <string>

struct A {
    std::string text;

    auto printer() {
        return [=]() {
            std::cout << this->text << "\n";
        };
    }
};

int main() {
    A a;
    auto printer = a.printer();
    a.text = "Hello, world!";

    printer();
}

[=]会起作用,因为它通过复制捕获了 lambda 主体中使用的所有自动变量。

这是示例输出: https : //www.ideone.com/kkXvJT

#include <iostream>
#include <functional>

class Foo
{
  int x, y, z;
  std::function<void(void)> _func;

public:
  Foo(int a): x(a), y(0), z(0)  {}

  void bar()
  {
    int a = 1,b,c;
    _func = [=]()
    {
      int u = this->x + a;
      std::cout << u << std::endl;
    };

    _func(); // lambda call
  }
};

int main()
{
  Foo obj(1);
  obj.bar();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM