I understand that .reserve()
reserves memory for the vector without actually modifying its size. But how is this implemented? How can you just reserve memory without allocating it?
EDIT: I'm asking specifically about how to reserve memory without allocating it, not about how std::vector
works in general
vector::reserve
does allocate memory, so your question about reserving memory without allocating is incorrect. The point is that reserving memory can be done without changing the vectors size. Basically a vector has two sizes, it's size and it's capacity. reserve
allocates memory and changes the capacity, but not the size.
At any given time the following is true 0 <= size <= capacity
. The capacity reflects the amount of memory allocated, the size reflects the number of constructed elements in that memory.