Search code examples
c++stlstddeque

Deque - how come "reserve" doesn't exist?


The standard STL vector container has a "reserve" function to reserve uninitialized memory that can be used later to prevent reallocations.

How come that the other deque container hasn't it?


Solution

  • Increasing the capacity of a std::vector can be costly. When a vector outgrows its capacity, the entire contents of the vector must be copied (or moved) to a larger reserve.

    It is specifically because std::vector resizing can be costly that vector::reserve() exists. reserve() can prepare a std::vector to anticipate reaching a certain size without exceeding its capacity.

    Conversely, a deque can always add more memory without needing to relocate the existing elements. If a std::deque could reserve() memory, there would be little to no noticeable benefit.