Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class members capturing inside constructor in c++ lambdas

Tags:

c++

lambda

Say we have Class A:

class A
{
    double x;
    double y;
    A(double, double);
    function <double(void)> F;
};

And the following constructor:

A::A(double a, double b)
{
    x = a;
    y = b;
    F = [this]() { return x + y; };
}

Why does the above constructor work while the following constructor causes a compilation error: member A::x is not a variable? (Same error for y.)

A::A(double a, double b)
{
    x = a;
    y = b;
    F = [x,y]() { return x + y; };
}

It seems I can capture only this and not the class members. Why is that?

like image 658
DifferentPulses Avatar asked Feb 08 '18 11:02

DifferentPulses


1 Answers

From cppreference – Lambda expressions:

Class members cannot be captured explicitly by a capture without initializer (as mentioned above, only variables are permitted in the capture list):

class S {
  int x = 0;
  void f() {
    int i = 0;
//  auto l1 = [i, x]{ use(i, x); };    // error: x is not a variable
    auto l2 = [i, x=x]{ use(i, x); };  // OK, copy capture
    i = 1; x = 1; l2(); // calls use(0,0)
    auto l3 = [i, &x=x]{ use(i, x); }; // OK, reference capture
    i = 2; x = 2; l3(); // calls use(1,2)
  }
};
like image 173
Aurel Bílý Avatar answered Sep 18 '22 09:09

Aurel Bílý