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

wco*_*ran 4 c++ lambda c++11

下面的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;
        // ...
     };
  }
};
Run Code Online (Sandbox Code Playgroud)

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

     _func = [this,=]() { // lambda func
        // ...
     };
Run Code Online (Sandbox Code Playgroud)

我在=下面遇到编译器错误this,:

  error: expected variable name or 'this' in lambda capture list 
Run Code Online (Sandbox Code Playgroud)

如果我试试这个

     _func = [=,this]() { // lambda func
        // ...
     };
Run Code Online (Sandbox Code Playgroud)

我明白了

  error: 'this' cannot be explicitly captured when the capture default is '='
Run Code Online (Sandbox Code Playgroud)

是否有抓取速度this和其他所有价值的速记?

bip*_*pll 7

正如cppreference所说:

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


Yak*_*ont 5

[=]*this做你想要的——它通过值和引用(或通过值)捕获非成员变量的任何内容this

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

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

两种默认捕获模式的捕获this方式相同。只有在中才能改变这一点。