Friday, September 21, 2007

STL vector and Some memory concerns.

I know STL vector is smart & very efficient . But when we using it lacks some memory deallocation functions other than destructor.
This is depending according to the version of Visual studio you are using . If you are using VS7 , the vector::clear() will remove all memory used by the vector. Otherwise , i mean if the compiler is VS2005 , you are in trouble. The vector hasn't any functions to release all memory used by it , except ~vector() (destructor).

Consider the following situations using VS2005

vector <int> myVec;
for(int i = 0 ; i < 10000; i++) myVec.push_back(i);
// ....some  codes.......

myVec.erase(myVec.begin()+1,myVec.end()); /*  removed all elements except the first.
                                                                     But memory still allocated , because vector
                                                                     reserved the memory for future allocations.*/

erase will mearly just removes  elements from the vector and calls destructor (->~_ty()). So still the memory is not deallocated(call myVec.capacity() to see the allocated bytes) .. What to do ? if you want to free up memory (Ofcourse u can delete , the last way).
One trick is to copy the contents to a new vector and again recopy it to the original vector , see below. Here the new vector(copy) will takes only the actual memory (it can be verifed using vector::capacity() ). During the recopy to original vector (myVec = copy) , the unwated memory is deleted.



    vector<int> copy  = myVec;
    myVec  = copy.


So now the memory will be delted.. Ofcourse it makes some perfomance imacpt due to copy operation . But In some cases it can save a lot of memory . It depends upon the type of applcation.

Note : I have checked this only with Visaul Studio 7 , 8's  implementaion of STL.

1 comment:

BapDeavaref said...

Please tell me if I should be posting in this category. Hey everyone my name is Andriana. Things I like jogging Here's a site I want to share diet program review. I am happy to reading more about this place