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

  • A+
Category:Languages

The lambda function below captures this (so bar() can access its instance vars) and the local variables 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;         // ...      };   } }; 

But if I want to capture many instance variables and wish to avoid explicitly naming them in the capture list, I do not seem to be able to do this:

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

I get a compiler error at the = following this,:

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

If I try this

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

I get

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

Is there a shorthand for capturing this and everything else by value?


As cppreference says:

[=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: