C ++ std :: vector内存/分配 [英] C++ std::vector memory/allocation
问题描述
贝利先生在先前关于向量容量的问题中说:
在当前的C ++中,可以保证在调用保留后不会发生任何重新分配,直到插入的大小超过了先前调用保留的值为止.在保留调用之前或之后,当大小在上一个保留调用的值和容量之间时,如果允许的话,允许实现者尽早重新分配.
In current C++ you are guaranteed that no reallocation occurs after a call to reserve until an insertion would take the size beyond the value of the previous call to reserve. Before a call to reserve, or after a call to reserve when the size is between the value of the previous call to reserve and the capacity the implementation is allowed to reallocate early if it so chooses.
因此,如果我理解正确,为了确保在超出容量之前不会发生任何重新分配,我是否必须预留两次?你能澄清一下吗?
So, if I understand correctly, in order to assure that no reallocation happens until capacity is exceeded, I must do reserve twice? Can you please clarify it?
我将向量用作这样的内存堆栈:
I am using vector as a memory stack like this:
std::vector<double> memory;
memory.reserve(size);
memory.insert(memory.end(), matrix.data().begin(), matrix.data().end()); // smaller than size
memory.resize(memory.capacity(), 0);
我需要保证上面没有发生重新分配.
I need to guarantee that reallocation does not happen in the above.
谢谢.
ps:我也想知道,除了向量以外,是否还有更好的方法来以类似方式管理内存堆栈
ps: I would also like to know if there is a better way to manage memory stack in similar manner other than vector
推荐答案
我认为您读错了该声明.储备金允许将capacity
设置为比所保留的金额更大的金额.特殊的语言是,如果您保留的存储量比上次(但在达到当前容量之前)要多,则允许重新分配实现.
I think you're reading the statement wrong. Reserve is allowed to set capacity
to a larger amount than what you reserved. The special language is to allow an implementation to reallocate if you're reserving more than you did the last time, but before you've reached the current capacity.
这篇关于C ++ std :: vector内存/分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!