https://en.cppreference.com/w/cpp/container/vector says:
The storage of the vector is handled automatically, being expanded and contracted as needed.
But I can't find a case where contraction would happen "as needed". None of the shrinking operations contract std::vector's capacity:
Leaves the capacity() of the vector unchanged
Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
This implies that iterators and references before the point of the erase don't get invalidated, which would not be the case if the capacity changed.
Iterators and references to the last element, as well as the end() iterator, are invalidated.
The same applies here.
shrink_to_fit() does contract the std::vector, but it was added in C++11 and the sentence above ("and contracted") isn't marked as only applying to C++11 and up. Also, an explicit call to shrink_to_fit() is not automatic ("The storage of the vector is handled automatically") and doesn't happen "as needed".
So when does std::vector automatically contract its storage?
shrink_to_fit
doesn't necessarily shrink the capacity to the size: it requests the vector to do so. It's up to the implementation to decide whether to fulfill this request.std::vector<int>{}.swap(my_vector);
shrink_to_fit
has some freedom, because it might not be possible to shrink to the exact size. For example, astd::vector<char>
of size 1 might keep more than 1 byte.