user695652 user695652 - 11 days ago 4x
C++ Question

Inserting an object having a non copyable field into an std::vector

I understand that the following code does not compile since the move constructor of A is deleted because the mutex is not movable.

class A {
A(int i) {}

std::mutex m;


int main() {
std::vector<A> v;

But if I want my
to be stored in an std container how should I go about this? I am fine with
being constructed "inside" the container.


std::vector::emplace_back may need to grow a vector's capacity. Since all elements of a vector are contiguous, this means moving all existing elements to the new allocated storage. So the code implementing emplace_back needs to call the move constructor in general (even though for your case with an empty vector it would call it zero times).

You wouldn't get this error if you used, say, std::list<A>.