问题
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 {
public:
A(int i) {}
private:
std::mutex m;
};
int main() {
std::vector<A> v;
v.emplace_back(2);
}
But if I want my A
to be stored in an std container how should I go about this? I am fine with A
being constructed "inside" the container.
回答1:
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>
.
来源:https://stackoverflow.com/questions/40049854/inserting-an-object-having-a-non-copyable-field-into-an-stdvector