As Vlad and Alf noted, std::string().swap(the_string) is a C ++ 98 way to free up the_string capacity, and the_string.shrink_to_fit() is a C ++ 11 path.
As for why clear() , erase() , resize() , etc. they donโt do this, itโs an optimization to reduce allocations when using the string again and again. If clear() freed the line bandwidth, you would usually have to redistribute the same area at the next iteration, which would take some time when the implementation could save, while maintaining capacity. This implementation is not guaranteed by the standard, but it is very common in implementations.
reserve() documented using
The calling reserve () with the res_arg argument is less than the capacity (), which is actually an optional reduction requirement. A call with the res_arg <= size () parameter is actually an optional reduction requirement to match.
which implies that implementations are more likely to free up capacity when calling reserve() . If I read them correctly, libC ++ and libstdC ++ make room when you call reserve(0) , but for the VC ++ library it is possible to make the opposite choice.
Edit: As Penelope says, the behavior of std::string here tends to be exactly the same as the behavior of std::vector .
source share