I wrote a program a few months ago using Vectors. I used the clear()
member function to "reset" the vectors, assuming that it would not only clear the items in the elements out and reset the size data member, but that it would also give the heap back the memory that was being used with it previously. Well, I stumbled onto a post about vectors saying that this is not the correct way to get memory back from the Vector, as using clear()
will not do it, but that one needed to use the swap method:
vector<MyClass>().swap(myVector);
I'm curious as to why we have to call the swap to delete the old memory? I assume this is more of a workaround, in that we are using the swap, but something else is happening. Is a destructor being called at all?
One last question, all of the articles that I've now read saying that clear()
doesn't deallocate memory that that the objects are "destroyed." Can anyone clarify what is meant by that? I'm unfamiliar with the vernacular. I assumed that if an object was destroyed, it was cleared out and the memory was given back to the heap, but this is wrong, so is the word "destroy" referring to just wiping the bits associated with each element? I'm not sure. Any help would be greatly appreciated. Thanks.