Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda capture by value captures at declaration point

Tags:

c++

c++11

lambda

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; } 
like image 267
perreal Avatar asked Jul 22 '12 10:07

perreal


People also ask

How do you capture a variable in lambda function?

Much like functions can change the value of arguments passed by reference, we can also capture variables by reference to allow our lambda to affect the value of the argument. To capture a variable by reference, we prepend an ampersand ( & ) to the variable name in the capture.

What is the correct syntax for lambda expression in C++11?

Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };

What does capture mean in lambda?

The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.

Can a lambda closure be used to create a C++11 thread?

Can you create a C++11 thread with a lambda closure that takes a bunch of arguments? Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.


1 Answers

Lambda functions are invoked by actually passing captured parameters to the function.

value is equal to 0 at the point where the lambda is defined (and value is captured). Since you are capturing by value, it doesn't matter what you do to value after the capture.

If you had captured value by 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.

like image 158
Ferruccio Avatar answered Sep 25 '22 09:09

Ferruccio