Is it guaranteed by the standard that
std::string will not give back allocated memory spontaneously if re-sized to a smaller size?
In other words:
std::string str = "Some quite long string, which needs a lot of memory"; str = ""; str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?
I ask because i'm depending on this to avoid heap fragmentation.
No guarantee whatsoever:
Effects: Alters the length of the string designated by
n <= size(), the function replaces the string designated by
*thiswith a string of length n whose elements are a copy of the initial elements of the original string designated by
n > size(), the function replaces the string designated by
*thiswith a string of length
size()elements are a copy of the original string designated by
*this, and whose remaining elements are all initialized to
The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.