What does the default allocator do when a std::vector is resized (via either reserve() or resize())?
-
The memory chunk internally used by the
std::vectoris actually resized. -
A new memory chunk is allocated, data is moved (e.g.,
std::moved) from the old memory chunk to the new one, and finally the old memory chunk is deallocated.
C++ allocators do not support anything like C’s
realloc. Whenevervectorneeds more memory, it has to allocate new storage, move from old to new, and deallocate the old.Either way,
reallocwouldn’t suitvector. With typical allocators,reallocwill only save you a heavy copy operation if you are shrinking its size, or in some cases growing by only a few bytes.vectordoesn’t ever shrink, and it only grows in very large steps.Note that move support is a new behavior in C++ 2011. Previous versions will copy.