How to store objects without copy or move constructor in std::vector?

前端 未结 4 467
情书的邮戳
情书的邮戳 2021-02-01 16:58

To improve efficiency of std::vector, it\'s underlying array needs to be pre-allocated and sometimes re-allocated. That, however, requires the creation and

4条回答
  •  梦毁少年i
    2021-02-01 17:11

    You can store elements without move or copy constructors in std::vector, but you simply have to avoid methods which require the elements to have move or copy constructors. Almost1 anything that changes the size of the vector (e.g., push_back, resize(), etc).

    In practice, this means you need to allocate a fixed-size vector at construction time, which will invoke the default constructor of your objects, which you can modify with assignment. This could at least work for std::atomic<> objects, which can be assigned to.


    1 clear() is the only example of a size-changing method that doesn't require copy/move constructors, since it never needs to move or copy any elements (after all, the vector is empty after this operation). Of course, you can never again grow your zero-sized vector again after calling this!

提交回复
热议问题