Why can't I initialize an array of objects if they have private copy constructors?

前端 未结 4 386
夕颜
夕颜 2021-01-24 08:34

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

4条回答
  •  借酒劲吻你
    2021-01-24 09:02

    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.)

提交回复
热议问题