2010年6月24日 星期四

Trick for releasing memory for C++ vector

For C++ vector, there's a huge problem that when you use either clear() or erase(), it won't release the memory for you. And there is "NO" direct way doing so. I searched on the internet and find one trick does that by using swap(). Here is the sample code by Tiyano (a student from Taiwan) explaining how it works.

#include
#include
using std::vector;
int main(void) {
vector A, B;
vector *C;
A.resize(1000);
printf("%d %d\n", A.size(), A.capacity());
A.clear();
printf("%d %d\n", A.size(), A.capacity());
A = B;
printf("%d %d\n", A.size(), A.capacity());
A.swap(B);
printf("%d %d\n", A.size(), A.capacity());
C = new vector;
C->resize(1000);
printf("%d %d\n", C->size(), C->capacity());
delete C;
C = new vector;
printf("%d %d\n", C->size(), C->capacity());
return 0;
}

The second method (new and delete) I'm not 100% sure it works, cuz in my case, the elements are pointers, so I adopt the first method which works.


沒有留言:

張貼留言