A T A T - 1 year ago 116
C++ Question

C++ vector reduce allocation size

When does a C++ vector dynamically reduce its allocated size in practice.

I know that the allocated space doubles upon an insert into a full vector, but it's not clear to me when the allocation is reduced. The classical hysteresis is to halve the allocation size upon removal from a 1/4-full vector.

Answer Source

It will never shrink the allocated memory in the absence of explicit direction to do so.

In C++11 there is a shrink_to_fit call that will ask the implementation to do this, but it may not reduce the allocated memory. In prior versions you have to create a new copy and swap away the old one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download