The code below prints 0, but I expect to see a 1. My conclusion is that lambda functions are not invoked by actually passing captured parameters to the functions, which is more intuitive. Am I right or am I missing something?
#include <iostream>
int main(int argc, char **argv){
int value = 0;
auto incr_value = [&value]() { value++; };
auto print_value = [ value]() { std::cout << value << std::endl; };
incr_value();
print_value();
return 0;
}
Lambda functions are invoked by actually passing captured parameters to the function.
valueis equal to 0 at the point where the lambda is defined (andvalueis captured). Since you are capturing by value, it doesn’t matter what you do tovalueafter the capture.If you had captured
valueby reference, then you would see a 1 printed because even though the point of capture is still the same (the lambda definition) you would be printing the current value of the captured object and not a copy of it created when it was captured.