5

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:

clear():

Leaves the capacity() of the vector unchanged

resize():

Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators

erase():

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.

pop_back():

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?

6
  • 1
    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.
    – paolo
    Commented Sep 29, 2022 at 9:02
  • 1
    If you want to shrink an empty vector back to 0 capacity, then swapping with a temporary vector will do this. eg std::vector<int>{}.swap(my_vector); Commented Sep 29, 2022 at 9:36
  • 3
    Maybe you could remove "and contracted" from that cppreference page (it is a wiki), indeed. Commented Sep 29, 2022 at 9:37
  • @paolo True. I reckon most implementations will honour the request though, otherwise there's not much point in having that function in the first place.
    – catnip
    Commented Sep 29, 2022 at 9:40
  • 1
    shrink_to_fit has some freedom, because it might not be possible to shrink to the exact size. For example, a std::vector<char> of size 1 might keep more than 1 byte.
    – BoP
    Commented Sep 29, 2022 at 10:18

1 Answer 1

0

After looking at the source code of the libstdc++, i didn't find any situation where the memory is freed.

It looks like the standard opens the door to complex memory management implementation but the widely known ones chose to never do that.

1
  • That source code is for GCC 4.6.3, which was released 9 years ago. The sources for GCC 12.2.0 can be found here. _M_guaranteed_capacity is only shrunk in shrink_to_fit() and swap().
    – glibg10b
    Commented Oct 22, 2022 at 3:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.