In C++11 shrink_to_fit
was introduce to complement certain STL containers (e.g., std::vector
, std::deque
, std::string
).
Synopsizing, its main functionality is to request the container that is associated to, to reduce its capacity to fit its size. However, this request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.
Furthermore, in a previous SO question the OP was discouraged from using shrink_to_fit
to reduce the capacity of his std::vector
to its size. The reasons not to do so are quoted below:
shrink_to_fit
does nothing or it gives you cache locality issues and it's O(n) to execute (since you have to copy each item to their new, smaller home). Usually it's cheaper to leave the slack in memory. @Massa
Could someone be so kind as to address the following questions:
- Do the arguments in the quotation hold?
- If yes, what's the proper way of shrinking an STL container's capacity to its size (at least for
std::vector
). - And if there's a better way to shrink a container, what's the reason for the existence of
shrink_to_fit
after-all?
shrink_to_fit
asks the implementation politely to get as closely to this goal as it's willing to. There is no better way, in general, to shrink a container. – Astigmatism