I just ran across some unexpected and frustrating behaviour while working on a C++ project. My actual code is a tad more complicated, but the following example captures it just
Assuming the copy constructor of Irritating
is disabled because it is expensive than perhaps it is best to manage them by reference:
vector> V = { new Irritating(), ... };
You could use shared_ptr
instead of unique_ptr
depending on the usage pattern.
(If you could modify Irritating you could give it a move constructor, take a look at move semantics)
If you really want them constructed in place than you could use aligned_storage
to make an array of storage for them and then placement new them in place. This would produce almost identical compiled code to what you want to do with your original request, but it is a little messier:
aligned_storage ::value>::type data[N];
new ((Irritating*) data+0) Irritating(...);
new ((Irritating*) data+1) Irritating(...);
new ((Irritating*) data+2) Irritating(...);
...
new ((Irritating*) data+N-1) Irritating(...);
(Dont forget to placement delete them at program exit.)