What is the difference between this line of code (Code 1)
auto l1 = [](auto a) { static int l = 0; std::cout << a << " " << ++l << std::endl; };
this line (Code 2)
static int l = 0;
auto l1 = [](auto a) { std::cout << a << " " << ++l << std::endl; };
and this? (Code 3)
int l = 0;
auto l1 = [l](auto a) mutable { std::cout << a << " " << ++l << std::endl; };
Main
l1("Joe");
l1("Joo");
l1(1.5);
Sometimes the int variable 'l' is shared between the calls and sometimes it is not. Having auto for one of the lambda's parameter, does it create multiple instances of the lambdas? I am not entirely sure how (Code 1) differs from (Code 2) and how (Code 2) differs from (Code 3). I was expecting (Code 3) to create multiple instances of the lambda so the output would be (Joe 1, Joe 2, 1.5 1) but turns out to be (Joe 1, Joe 2, 1.5 3).
In the first sample there are as many static variables as there are instantiations of the lambda. And there could be many of them because you specify the parameter as
auto, that makes your lambda some sort of a template.The third code captures
lby value each time the lambda is created, and creates a local copy of it, so nothing is shared at all.Let's see an example. Let's create a function
f()with the lambda defined inside, and call the function twice:This code calls the same lambda 3 times with the
intvalue, and 3 times with thechar.Code 1:
lis shared between the instantiations, so we would see 2 different variables used:The second call to
f()allows you to reuse the static variable, but there are two different variables for two distinct types.Code 2:
lis the only static variable and is shared between all lambdas:Code 3: you have one lambda created per each function invocation, and this lambda uses the only instance of the variable
lthat is captured on the time of creation:If you run this code again, you would see that the
lis recreated again, and the result would be repeated.