|
|
|
|
|
by catnaroek
3567 days ago
|
|
In C++, you can explicitly specify whether lambdas capture by value or by reference, on a per captured variable basis. Most reasonable programmers would capture `int`s by value. For instance, this program is guaranteed to print all numbers 0..9, not necessarily in order: #include <iostream>
#include <thread>
#include <vector>
int main()
{
std::vector<std::thread> vec;
for (int i = 0; i < 10; ++i)
vec.emplace_back([i] () { std::cout << i; });
for (auto & thr : vec)
thr.join();
std::cout << std::endl;
return 0;
}
Reusing the loop counter variable across iterations in an imperative language is perfectly fine. The confusion comes from capturing a mutable environment by reference, which is a confusing (and hence bad) default. |
|