是否在移动std :: vector时需要保留容量? [英] Is the capacity required to be preserved when moving a std::vector?
问题描述
请考虑以下代码:
std::vector vec;
vec.reserve(500);
size_t cap = vec.capacity();
std::vector newVec = std::move(vec);
assert(cap == newVec.capacity());
在几乎所有执行过程中,这都可以工作。我不在乎什么实现。我想知道标准的要求。移动到向量
与原始容量相同吗?或者将assert触发器?
In pretty much any implementation you run across, this will work. I don't care about what implementations do. I want to know what the standard requires. Will the moved-to vector
have the same capacity as the original? Or will the assert trigger?
推荐答案
看看标准,看起来什么都不需要从move构造函数, amaurea说,如果移动构造函数试图分配或释放内存,它将完全击败移动语义的目的,所以我希望所有实现中的容量保持不变。
Looking at the standard, it appears that nothing is required from the move constructor, however as @amaurea says, it would completely defeat the purpose of move semantics if the move constructor were to try and allocate or deallocate memory, so I would expect the capacity to remain the same in all implementations.
23.2.1一般容器需求
>
X u(a);
X u = a;
声明/注释前/后条件
需要: T
是CopyInsertable为X(见下文)。
post: u == a
Requires: T
is CopyInsertable into X (see below).
post: u == a
标准只需要 newVec = = vec
。由于 std :: vector :: operator ==
, newVec
不需要考虑容量与 vec
相同的容量。
The standard only requires that newVec == vec
. As capacity is not taken into consideration for std::vector::operator==
, newVec
need not necessarily have the same capacity as vec
.
这篇关于是否在移动std :: vector时需要保留容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!