To improve efficiency of std::vector
, it\'s underlying array needs to be pre-allocated and sometimes re-allocated. That, however, requires the creation and
That requires however the creation of objects of type T with a copy ctor.
That is not entirely right, as of C++11, if you use the constructor of std::vector
which will default construct a number of elements, then you don't need to have a copy or move constructor.
As such, if no threads are added or deleted from your pool, you can then just do:
int num = 23;
std::vector vec(num);
If you want to add or delete things dynamically, then you have to use an indirection.
std::vector
+ std::unique_ptr
as already proposedstd::deque
, that allows you to neatly use it with range based for loops or std-algorithms and avoids all indirections. (Which only allows additions)std::list/forward_list
this solution is similar to number one, however it has the additional benefit of easier usage with range based for and algorithms. It's probably the best if you are only accessing the elements sequentially as there is no support for random-access.Like this:
std::deque deq;
deq.emplace_back();
deq.emplace_back();
for(auto& m : deq) {
m.lock();
}
As a final note, std::thread
is of course moveable, so you can use std::vector
+ std::vector::emplace_back
with it.