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?
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)
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With