I seems to miss some point in lambda mechanism in C++. Here is the code:
std::vector<int> vec (5);
int init = 0;
std::generate(begin(vec), end(vec), [init]() mutable { return ++init; });
for (auto item : vec) {
std::cout << item << " ";
}
std::cout << std::endl << init << std::endl;
If there is no mutable
it wouldn't compile because I'm changing init
in lambda.
Now, as I understand lambda is called for each vector's item with a new fresh copy of init
which is 0.
So, 1 must be returned every time.
But the output of this piece of code is:
1 2 3 4 5
0
It looks like generate
captures by copy init
only once at the beginning of its execution. But why? Is it supposed to work like this?