The vector
and string
types provide members, described in Table 9.10, that let us interact with the memory-allocation part of the implementation. The capacity
operation tells us how many elements the container can hold before it must allocate more space. The reserve
operation lets us tell the container how many elements it should be prepared to hold.
reserve
does not change the number of elements in the container; it affects only how much memory the vector
preallocates.
A call to reserve
changes the capacity of the vector
only if the requested space exceeds the current capacity. If the requested size is greater than the current capacity, reserve
allocates at least as much as (and may allocate more than) the requested amount.
If the requested size is less than or equal to the existing capacity, reserve
does nothing. In particular, calling reserve
with a size smaller than capacity
does not cause the container to give back memory. Thus, after calling reserve
, the capacity
will be greater than or equal to the argument passed to reserve
.
As a result, a call to reserve
will never reduce the amount of space that the container uses. Similarly, the resize
members (§ 9.3.5, p. 352) change only the number of elements in the container, not its capacity. We cannot use resize
to reduce the memory a container holds in reserve.
Under the new library, we can call shrink_to_fit
to ask a deque, vector
, or string
to return unneeded memory. This function indicates that we no longer need any excess capacity. However, the implementation is free to ignore this request. There is no guarantee that a call to shrink_to_fit
will return memory.