Building an "array" of objects that cannot be copied

I have a class that is not explicitly copied (stream, so there is no copy semantics that make sense), and I want to have a large "array" of them, identically constructed with a constructor that is different from the standard one. Note that the array has a fixed size.

I can only use the default constructor with C ++ arrays if I do not initialize each of them myself.

Thread myArray[128]; // uses default constructor - wrong 

I can explicitly specify the constructors and parameters of the object, but this detailed and ugly

 Thread myArray[128] = { Thread(params,...), Thread(params,...), ... x 128 ; // ugly 

It seems I can not use stl vectors because the object is not copied - an event, although the vector never changes size. I think the constructor really copies!

 std::vector<Thread> myVector(128, Thread(params,...));// won't compile 

The way I do this is an array of smart pointers and an initialization loop, but maybe I missed something:

Is there any other way - maybe with forced containers or with another type of container?

+7
source share
4 answers

The vector of smart pointers, with each instance dynamically allocated, is by far the easiest way. Otherwise (and I would only do this if absolutely necessary), you can more or less emulate what std::vector does internally. Something along the line:

 union { double just_to_ensure_alignment; unsigned char data[ sizeof(Thread) * elementCount ]; } array; // construct... for ( int i = 0; i != elementCount; ++ i ) new (data + i * sizeof(Thread)) Thread(params,...); // access... Thread& getAt( int i ) { return reinterpret_cast<Thread*>( data + i * sizeof(Thread) ); } 

(I would wrap this in a class, if only to be able to use operator[] instead of getAt .)

+3
source

It may seem completely crazy (and probably it is), but ...

 struct ThreadInitValues{ // your actual params int i; float f; }; struct Thread{ Thread(int i = _init.i, float f = _init.f) : _i(i) , _f(f) {} static ThreadInitValues _init; private: // uncopyable Thread(Thread const&); Thread& operator=(Thread const& other); // your actual member int _i; float _f; }; ThreadInitValues Thread::_init; int main(){ Thread::_init.i = 5; Thread::_init.f = 3.14f; Thread arr[128]; } 

Maybe this will work for you. :) Of course, now you need to keep track of if the array is initialized in the multi-threaded code itself ...

+6
source

For new compilers that support r-value references, AFAIK vector elements do not need to be copied. To use it without copying, you need to use push_back (each time creating a new object), because creating multiple objects from one is copying :).

If this method is not available, try boost :: ptr_vector or std :: vector boost :: shared_ptr.

+1
source

I'm not such a big programmer. But did you try it

 std::vector<YourObject *> temp_Vec; for(int i=0;i<128;++i) temp_Vec.push_back(new YourObject(arguments)); 
0
source

All Articles