Shrink to Fit
Prev | Chapter 13. String Classes | Next

## Shrink to Fit

From GCC 3.4 calling `s.reserve(res)` on a `string s` with `res < s.capacity()` will reduce the string's capacity to `std::max(s.size(), res)`.

This behaviour is suggested, but not required by the standard. Prior to GCC 3.4 the following alternative can be used instead

          std::string(str.data(), str.size()).swap(str);

This is similar to the idiom for reducing a `vector`'s memory usage (see FAQ 5.9) but the regular copy constructor cannot be used because libstdc++'s `string` is Copy-On-Write.

Prev | Up | Next
Tokenizing | Home | CString (MFC)