标准对矢量调用 clear 如何改变容量有什么说法?

2021-12-21 00:00:00 language-lawyer vector c++

该网站暗示清除矢量可能会改变容量:

This website implies that clearing a vector MAY change the capacity:

http://en.cppreference.com/w/cpp/container/矢量/清除

很多实现不会在调用后释放分配的内存到clear(),有效地留下了vector的capacity()不变.

Many implementations will not release allocated memory after a call to clear(), effectively leaving the capacity() of the vector unchanged.

但根据@JamesKanze 的说法,这是错误的,清除的标准指令不会改变容量.

But according to @JamesKanze this is wrong and the standard mandates that clear will not change capacity.

标准怎么说?

推荐答案

取决于您正在查看的标准版本,clear 定义为等价于 erase(begin(), end()),或(在 C++11 中):
"销毁a中的所有元素.使所有元素失效引用、指针和迭代器a 和的元素可能会使结束迭代器."

Depending on the version of the standard you are looking at, clear is defined as the equivalent of erase(begin(), end()), or (in C++11):
"Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator."

在任何情况下都不允许修改容量;以下代码由安全保证标准:

In neither case is it allowed to modify the capacity; the following code is guaranteed safe by the standard:

std::vector<int> v;
for (int i = 0; i != 5; ++ i) {
    v.push_back(i);
}
assert(v.capacity() >= 5);
v.clear();
assert(v.capacity() >= 5);
v.push_back(10);
v.push_back(11);
std::vector<int>::iterator i = v.begin() + 1;
v.push_back(12);
v.push_back(13);
*i = 42;        //  i must still be valid, because none of 
                //  the push_back would have required an
                //  increase of capacity

(C++11措辞变化的原因:委员会不想为 clear 要求 MoveAssignable,这会如果它是根据 erase 定义的,情况就是如此.)

(The reason for the change in wording in C++11: the committee didn't want to require MoveAssignable for clear, which would have been the case if it were defined in terms of erase.)

相关文章