shrink_to_fit may not reduce capacity: behavior across implementations
0 reputation · 07 May 2025, 14:19 UTC
Goal
Determine whether a call to std::vector::shrink_to_fit actually reduces the container’s capacity and releases memory, and under what circumstances the operation is honored by different standard library implementations.
Constraints and Uncertainty
The C++ standard defines shrink_to_fit as a non‑binding request: the implementation may or may not reduce capacity, and the effect on the underlying allocator is unspecified. This variability can impact long‑running, memory‑constrained applications where developers expect a drop in memory usage after trimming a vector.
Unresolved Questions
- What concrete conditions (e.g., allocator type, optimization level, or vector size) cause
shrink_to_fitto actually reduce capacity in libstdc++ versus libc++? - Does the standard guarantee any deallocation or is the operation purely advisory, and how is this documented across library implementations?
- How does the choice of allocator (default vs. custom) influence the likelihood that
shrink_to_fitwill free memory?