Will vector ever shrink in size

Hi all,
I was wondering will std::vector ever shrink in size. for example if it sees that it's capacity is much larger than it's size.
I know from experience that vector in gcc4.3 only grows and never shrinks but I don't know whether this is the ISO standard or just the common implementation.
for example I don't know whether this code guarantees that the .resize(0) won't release the memory:
1
2
3
4
5
vector<int> v;
for (size_t i; i<10000; i++) {
    v.push_back(i);
}
v.resize(0);

or what this does?
1
2
3
vector<int> v;
v.reserve(1000000);
v.reserve(10);

will it release the memory?

Thanks in advance
In the second example the memory will not be released, as the standard guarantees that reserve only reallocates when the current capacity is lower than the requested one.
However, I am unsure about the first one. I cannot find any part in the standard that prohibits a reduction of capacity when erasing all elements. For what it's worth, all implementations I know of do not reduce the capacity.
You can use member function void shrink_to_fit(); if your compiler supports the C++ 2011 Standard.
If you use an old compiler you can use swap member function with an empty vector to release memory.

As for your example neither the first nor the second releases memory.
Last edited on
You could always use a list if you are that concerned with memory management.
Thanks you. In didn't know about the shrink_to_fit() function. In any case another thread in this forum just discusses this issue so I am closing this one.
Topic archived. No new replies allowed.