>> I'm not sure it works even if it's moveable because there's no guarantee it will make copy elision everywhere it's needed.
Of course it works, since std::thread is movable but non-copyable, std::vector<std::thread> will be movable but non-copyable too. So the compiler type checking will make sure it's not copied anywhere.
This works like a charm (with GCC 4.7-ish from git):
#include <thread>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<std::thread> threads;
for(int i = 0 ; i < 10 ; ++i)
threads.push_back(std::thread([=]() { std::cout << i << std::endl; }));
std::for_each(threads.begin(), threads.end(), [](std::thread& thread) { thread.join(); });
}
>> Better use std::generate.
I used to nitpick about not using std::algorithms when they're available, but I grew out of it. I figured out that std::algos are very limited (esp. in c++98), and while you can use them to do stuff, it usually takes a significant amount of brainpower only to reformulate your problem to be suitable for std::algorithms. There are so many situations where a good old loop will produce more readable code faster, so why bother with the standard algorithms if they're not a perfect fit?
Btw. has std::generate improved at all in C++11? It's one of the most limited algorithms in c++98.
>> it usually takes a significant amount of brainpower only to reformulate your problem to be suitable for std::algorithms
That's true, but the final result generally ends up with less bugs and better thought out algorithms. It forces you to think "what problem am I currently trying to solve?"
Of course it works, since std::thread is movable but non-copyable, std::vector<std::thread> will be movable but non-copyable too. So the compiler type checking will make sure it's not copied anywhere.
This works like a charm (with GCC 4.7-ish from git):
>> Better use std::generate.I used to nitpick about not using std::algorithms when they're available, but I grew out of it. I figured out that std::algos are very limited (esp. in c++98), and while you can use them to do stuff, it usually takes a significant amount of brainpower only to reformulate your problem to be suitable for std::algorithms. There are so many situations where a good old loop will produce more readable code faster, so why bother with the standard algorithms if they're not a perfect fit?
Btw. has std::generate improved at all in C++11? It's one of the most limited algorithms in c++98.