When std::function is created with a lambda, the std::function internally makes a copy of the lambda object. Thus, our call to fn() is actually being executed on the copy of our lambda, not the actual lambda.
According to the statements above, what is the point of passing a lambda by 'reference using &' or passing by 'value' in the code below while the std::function always makes a copy of the lambda object?
In other words, in the code below, which part of lambda will OR will not be modified/effected when the parameter of 'invoke' function is passed by reference or value?
#include <iostream>
#include <functional>
void invoke(const std::function<void(void)>& fn) // # PASS LAMBDA BY REFERENCE*********************
{
fn();
}
int main()
{
int i{ 0 };
// Increments and prints its local copy of @i.
auto count{ [i]() mutable {
std::cout << ++i << '\n';
} };
invoke(count);
invoke(count);
invoke(count);
return 0;
}
#include <iostream>
#include <functional>
void invoke(const std::function<void(void)> fn) // # PASS LAMBDA BY VALUE*********************
{
fn();
}
int main()
{
int i{ 0 };
// Increments and prints its local copy of @i.
auto count{ [i]() mutable {
std::cout << ++i << '\n';
} };
invoke(count);
invoke(count);
invoke(count);
return 0;