I’m currently learning about concurrency in C++ and came across using a vector of threads, which I believe will be possible in C++0x. However, my current compiler doesn’t appear to have an implementation of move-aware containers and so I get errors generated because std::thread::thread(const std::thread&) is deleted, ie I can only use the move constructor/move assignment with std::thread.
Am I correct in thinking I could circumvent this issue by writing a custom allocator using
void MyAllocator::construct (pointer p, reference val)
/* should be non-const reference to val because using move constructor? */
{
new ((void*)p) T (std::move(val));
}
rather than
void allocator::construct (pointer p, const_reference val)
{
new ((void*)p) T (val);
}
? Or some other variation on this theme (possibly using an overload of MyAllocator::construct).
NB: This is mainly intended to be a short-term educational exercise and well enough performing work around to play around with threads in containers. I’d only be using MyAllocator in this context. However, please also point me at any libraries that may have this implemented so I can have a poke around the source.
If your compiler doesn’t provide a move-aware
std::vectorthen you’ll have to write your own specialization ofstd::vector<std::thread>rather than just provide a custom allocator. The whole C++03vectorinterface relies on copying:push_back()copies elements in;resize()initializes the empty elements with a copy of the element passed as the second parameter (even if that is the default value ofT());resize(),reserve(),insert(),erase()andpush_back()will copy elements if the vector needs reallocating, or elements otherwise need moving around, and so forth.This is such a common problem that I’ve included such a specialization with my (commercial) just::thread implementation of
std::thread.