xersi xersi - 3 months ago 7
C++ Question

Trying to understand lambdas

Here is the reference:
Lambdas

What I do not understand is this:

int multiplier = 5;
auto timesFive = [multiplier](int a) { return a * multiplier; };
std::cout << timesFive(2) << '\n'; // Prints 10

multiplier = 15;
std::cout << timesFive(2) << '\n'; // Still prints 2*5 == 10 (???) - Should it be 30?


When the program calls the
timesFive()
the second time, I expect the result to be 30. But why is the result
Still prints 2*5 == 10
, not
prints 2*15 == 30
? Perhaps the lambda function somehow cannot track the value of
multiplier
, even though we have already tried to capture it?

And what is the way to get the desired result?

Answer

You captured multiplier by value, which means it was copied into the lambda. You need to capture it by reference:

int multiplier = 5;
auto timesFive = [&multiplier](int a) { return a * multiplier; }; 
std::cout << timesFive(2);

multiplier = 15;
std::cout << timesFive(2);