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

Viewed 6711

To improve efficiency of std::vector<T>, it's underlying array needs to be pre-allocated and sometimes re-allocated. That, however, requires the creation and later moving of objects of type T with a copy ctor or move ctor.

The problem that I am having is that T cannot be copied or moved because it contains objects that cannot be copied or moved (such as atomic and mutex). (And, yes, I am implementing a simple thread pool.)

I would like to avoid using pointers because:

  1. I do not need a level of indirection and so I do not want one.
  2. (Pointers are less efficient and increase complexity. Using pointers increases memory fragmentation and decreases data locality which can (but not necessarily must) cause a noticeable performance impact. Not so important, but still worth consideration.)

Is there a way to avoid a level of indirection here?

UPDATE: I fixed some incorrect assumptions and re-phrased the question, based on feedback in comments and answers.

4 Answers

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!

Related