How to free memory held by a container?
I have a test program like this:
So when you have to free the memory, just call reset(large_str).
int main() {The last line of the output is:
string large_str;
for (int i = 1; i <= 1000; ++i) {
string slice(100*i, 'X');
large_str += slice;
large_str.clear ();
printf ("size: %-5d, capacity: %-5d\n", large_str.size(), large_str.capacity());
}
}
size: 0, capacity: 131043The question is:
It is very obvious that the string container still holds memory that it allocated for the longest string it contained. How to deallocate this memory, without destructing the object?Thanks to James Kanze who posted an answer in this usenet thread, here is an elegant solution for this problem.
template <typename Container>
void reset( Container& c ) {
Container().swap( c ) ;
}
So when you have to free the memory, just call reset(large_str).
Comments