10

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?

1 Answer 1

9

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)
  }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.