I have a class that’s inhenerently non-copyable (a thread, so there’s no copy semantics that make sense), and I want to have a largeish ‘array’ of these, identically constructed with a non-default constructor. Note that the array is fixed size.
I can only use the default constructor with C++ arrays, unless I initialise each one independently.
Thread myArray[128]; // uses default constructor - wrong
I can list the object constructors and parameters explicitly, but that’s verbose and ugly
Thread myArray[128] = { Thread(params,...), Thread(params,...), ... x 128 ; // ugly
It seems I can’t use stl vectors because the object is non-copyable – event though the vector never changes size. I guess the constructor actually does copying!
std::vector<Thread> myVector(128, Thread(params,...));// won't compile
The way I’ve though of doing this is with an array of smart pointers and an initialization loop, but maybe I’m missing something:
Is there any other way – maybe with boost containers, or a different container type?
A vector of smart pointers, with each instance dynamically
allocated, is definitely the simplest way. Otherwise (and I’d
only do this if absolutely necessary), you can more or less
emulate what
std::vectordoes internally. Something along thelines of:
(I’d actually wrap this in a class, if only to be able to use
operator[]instead ofgetAt.)