I came across the web (don’t recall where) a note that says that MS c++ stl containers have a memory leak in their clear() API.
Therefore if you have a:
void main()
{
std::vector<int> vVec;
for(int i =0; i < 100; i++)
vVec.push_back(i);
vVec.clear();
}
Therefore the memory allocated on the heap for the vector is not really released…
The note said (as far as i recall) the following technique to make sure the memory is really released…
void main()
{
std::vector<int> vVec;
for(int i =0; i < 100; i++)
vVec.push_back(i);
vVec.clear();
vector<int>(vVec).swap(vVec);
}
Do you have experience with such? is the above true? and if yes, what actually happening here?
(and last question, sorry, is this true for all other stl containers?)
Thanks,
It’s not a memory leak; it’s the required behavior (by the standard).
std::vector<>::clear()is not allowed to lower the capacity, and thuscannot free its buffer. The memory will be freed when the
destructor is called, and in
swap, the buffers will be swapped, so in, the temporary object gives
vVecits (empty) buffer, and receives thenon-empty buffer of
vVec, which it deletes at the end of the fullexpression.
This is normally not needed, or even wanted, after
clear; if you wanta completely new vector, just declare one. On the other hand, if you’ve
been filling a vector gradually, it could easily have a capacity of more
than is needed, and an excessively large buffer. In this case:
will first make a (temporary) copy with an exactly sized buffer, then
swap buffers with
vVec. The results will be thatvVechas acapacity equal to its size, and no more. (Formally, this isn’t
guaranteed by the standard anywhere, but in practice, it corresponds to
all of the implementations I know of.)