将具有非可复制字段的对象插入std :: vector中 [英] Inserting an object having a non copyable field into an std::vector
问题描述
我知道以下代码不会编译,因为A的move构造函数被删除,因为互斥不可移动。
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);
}
但如果我想要 A
要存储在std容器中我应该怎么走这个?我很好与 A
正在构建内部的容器。
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.
推荐答案
std :: vector :: emplace_back
矢量的能力。由于向量的所有元素都是连续的,这意味着将所有现有元素移动到新分配的存储。因此,实现 emplace_back
的代码通常需要调用move构造函数(即使对于一个空向量,它将被称为零次)。
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).
如果你使用 std :: list< A>
,你不会得到这个错误。
You wouldn't get this error if you used, say, std::list<A>
.
这篇关于将具有非可复制字段的对象插入std :: vector中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!