为什么不在 GotW 54 中调整大小并清除作品?
参考 HerbSutter 的文章 Gotw 54,他解释了
正确的方法“缩小以适应” 矢量或双端队列和
完全清除向量或的正确方法 deque
我们可以只使用
container.resize()
和用于上述任务的container.clear()
或者我错过了什么?
Referring to article Gotw 54 by HerbSutter, he explains about
The Right Way To "Shrink-To-Fit" a
vector or deque andThe Right Way to Completely Clear a vector or
deque
Can we just use
container.resize()
andcontainer.clear()
for the above task
or am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向量包含两种不同的东西:
大小
与容量
。如果您只是调整
向量的大小,则不能保证容量(保留多少内存)一定会改变。resize
是一个与您使用了多少容量相关的操作,而不是矢量容量有多少。例如。
最后,不应该在每次操作时都改变容量,因为这会带来大量的内存分配/释放开销。他是说,如果您需要“释放”向量保留的内存,就这样做。
There are two different things that a vector holds:
size
Vscapacity
. If you justresize
the vector, there is no guarantee that the capacity(how much memory is reserved) must change.resize
is an operation concerned with how much are you using, not how much the vector capacity is.So for example.
In the end, capacity should not changed on every operation, because that would bring a lot of memory allocation/deallocation overhead. He is saying that if you need to "deallocate" the memory reserved by vector, do that.
resize() 和clear() 都不起作用。向量的
.capacity()
保证至少与向量的当前size()
一样大,并且保证至少与向量的当前size()
一样大reserve()
d 容量。此外,这个 .capacity()
不会缩小,因此它也至少与之前的size()
或reserve()
一样大>化。现在,向量的
.capacity()
只是它保留的内存。通常并非所有内存都包含对象。调整大小会删除对象,但不会回收内存。向量只能在分配更大的缓冲区时回收其内存缓冲区。交换技巧的工作原理是将所有对象复制到更小、更合适的内存缓冲区。之后,原来的内存缓冲区就可以被回收。这似乎违反了前面的说法,即向量的内存缓冲区只能增长。但是,通过交换技巧,您暂时拥有 2 个向量。
Neither resize() nor clear() work. The
.capacity()
of a vector is guaranteed to be at least as big as the currentsize()
of the vector, and guaranteed to be at least as big as thereserve()
d capacity. Also, this .capacity()
doesn't shrink, so it is also at least as big as any previoussize()
orreserve()
ation.Now, the
.capacity()
of a vector is merely the memory it has reserved. Often not all of that memory cotains objects. Resizing removes objects, but doesn't recycle the memory. A vector can only recycle its memory buffer when allocating a larger buffer.The swap trick works by copying all ojects to a smaller, more appropriate memory buffer. Afterwards, the original memory buffer can be recycled. This appears to violate the previous statement that the memory buffer of a vector can only grow. However, with the swap trick, you temporarily have 2 vectors.
向量有大小和容量。它可能保存 X 个元素,但还为 Y 元素存储了未初始化的内存。在典型的实现中,擦除、调整大小(当调整为较小尺寸时)和清除不会影响容量:如果您想稍后向其中添加新项目,向量会保留内存。
The vector has size and capacity. It may hold X elements but have uninitialized memory in store for Y elements more. In a typical implementation erase, resize (when resizing to smaller size) and clear don't affect the capacity: the vector keeps the memory around for itself, should you want to add new items to it at a later time.