From a previous question about vector capacity, Mr. Bailey said:
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.
thank you.
ps: I would also like to know if there is a better way to manage memory stack in similar manner other than vector
I think you’re reading the statement wrong. Reserve is allowed to set
capacityto 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.