I am learning about lambdas in modern C++ and I am trying to understand about captures.
My lambda below captures the variable x
by value. However, why do I get the output value 11
even through I set 100
as a new value for x
prior to the call to add_to_x(int)
.
Q1 Does the resolution of a by-copy captured variable x
in a lambda happen only at the point of the lambda definition and not at its usage which is why it has used x=1
rather than the x=100
?
int main(int argc, char** argv) {
int x = 1;
auto add_to_x = [x] (int i) {
return i + x;
};
x = 100;
cout << "add_to_x=" << add_to_x(10) << endl;
// prints "add_to_x=11" but I was expecting "add_to_x=110"
}
However, if I capture by-reference, it used x=100
and I got 110
.
Q2 How did it happen that by adding the &
to the captured variable (turning it to a capture by-reference) it suddenly considered to use the x=100
?
int main(int argc, char** argv) {
int x = 1;
auto add_to_x = [&x] (int i) {
return i + x;
};
x = 100;
cout << "add_to_x=" << add_to_x(10) << endl;
// prints "add_to_x=110"
}
I tried a couple of combinations but it behaved the same.
Sephiroth is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3