Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector Memory Usage - Is it ever freed?

Tags:

c++

stl

I know that vectors double in size whenever their capacity() is exceeded. This operation takes some time which is why vectors are supposed to have amortized constant time for addition of elements with push_back().

  1. What I'm wondering is... what happens when a vector shrinks so that its size() is less than half of the capacity().

  2. Do vectors ever relinquish the memory which they use, or is it just gone until the vector is destroyed?

It could be a lot of wasted memory if they don't shrink in size ever, but I've never heard of them having that feature.

like image 498
John Humphreys Avatar asked Aug 24 '11 15:08

John Humphreys


2 Answers

No, it is never freed (i.e. capacity is never reduced) until destruction. A common idiom for freeing up some memory is to create a new vector of the correct size, and use that instead:

std::vector<type>(originalVector).swap(originalVector);

(inspired by "More Exceptional C++", Item #7)

like image 114
SSJ_GZ Avatar answered Oct 07 '22 22:10

SSJ_GZ


If you want to make sure your vector uses as little space as possible, you can say:

std::vector<Foo>(my_vector).swap(my_vector);

You could also call the shrink_to_fit() member function, but that is just a non-binding request.

like image 33
fredoverflow Avatar answered Oct 07 '22 22:10

fredoverflow