Why don't std::vector's elements need a default constructor?

前端 未结 4 1524
失恋的感觉
失恋的感觉 2020-12-02 23:22

And how can I write my own array class to not need a default constructor for its elements? Right now, when I do the new [] to allocate space, I need a default const

4条回答
  •  春和景丽
    2020-12-02 23:49

    You could allocate a block of bytes, then use placement new to make new instance of T (your parametric type) via copy constructor (not default constructor of course) when new items are pushed to the vector's back. This will not allow to to make "a vector of N default-initialized Ts" (which std::vector can make - which is why it does need T to have a default constructor for this purpose), but you could make vectors that start empty and can have Ts pushed onto them.

提交回复
热议问题