Is std::string guaranteed not to give back memory spontaneously?

  • A+
Category:Languages

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:

[string.capacity]/7

Effects: Alters the length of the string designated by *this as follows:

(7.1) If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.
(7.2) If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.

The emphasized part show that the Committee let the implementation choose freely between an invalidating operation and a more conservative one.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: