The usual shrink-to-fit idiom won't work on copy-on-write implementations of
std::string . What usually does work is to call
s.reserve(0) or to fake the
string out by writing
string(s.begin(), s.end()).swap(s); to use the iterator range constructor. In practice, these work to shed excess capacity. (Better still,
std::string implementations are abandoning copy-on-write, which is an outdated optimization; see [Sutter02].)