Class members capturing an internal constructor in C ++ lambdas

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 this constructor work, and 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 only capture this , not the members of the class. Why is this?

+7
c ++ lambda
source share
1 answer

From cppreference - Lambda expressions :

Class members cannot be captured explicitly by a capture without an initializer (as mentioned above, only variables are allowed 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) } }; 
+9
source share

All Articles