gpt4 book ai didi

c++ - container.clear() 是否释放/重新分配内部缓冲区?

转载 作者:可可西里 更新时间:2023-11-01 15:48:35 24 4
gpt4 key购买 nike

如果我有一个容器并在其上调用 clear(),那么只是会破坏内部的所有元素还是它实际上也在内部释放/分配新内存?这种行为是否超出了 C++ 标准的范围?

这归结为:

unordered_set<int> mySet { 1, 2, 3, 4, 5 };
mySet.reserve(1000);
mySet.clear();

//Is this pointless/redundant
//or should I treat my container like it was just constructed?
mySet.reserve(1000);

对 ideone ( http://ideone.com/XQi8IT ) 的快速测试表明,在调用清除后,内部内存缓冲区会保留。因此,至少对于 unordered_set 上的新版本 g++ 是这样。我的问题是 1) 标准是怎么说的,如果有的话,以及 2) 这种行为是否在所有容器中都是一致的。

最佳答案

未指定内存发生了什么。它只是定义了以下要求:

对于序列容器,我们对 clear() 有以下要求:

[C++11 §23.2.3] 表 100

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.

post: a.empty() returns true

其中并没有真正提到任何关于内存的事情。对于关联容器,我们对 clear() 有以下要求:

[C++11 §23.2.4] 表 102

a.erase(a.begin(),a.end())

这导致 erase(...) 要求是:

erases the element pointed to by q. Returns an iterator pointing to the element immediately following q prior to the element being erased. If no such element exists, returns a.end()

同样,没有提及容器内存缓冲区的容量。然后我们有具有类似措辞的无序关联容器:

[C++11 §23.2.5] 表 103

Erases all elements in the container. Post: a.empty() returns true

总的来说,标准没有提到在clear 之后内部内存缓冲区会发生任何事情。所以这是未指定的行为,可能因不同的实现而异。

由于 reserve 并非在所有容器中都可用(这确实会改变容量),而且下一个最好的东西(shr​​ink_to_fit)也不是,因此似乎没有持续清除容器内部内存的好方法。

关于c++ - container.clear() 是否释放/重新分配内部缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28097419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com