Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • if the new string allocation is less than the previous allocation, no allocation occurs. If the new string requires more allocation than the current, a reallocation occurs. Similar to a std::vector. Commented Sep 25, 2018 at 10:19
  • Strings reuse their buffers when assigned to shorter strings, so in your program there is only one allocation for the string. Unfortunately I can't find conveniently any citation from the standard on mobile Commented Sep 25, 2018 at 10:20
  • 1
    Even if a string did "give back memory spontaneously", that is insufficient to avoid heap fragmentation. A string uses an allocator (by default, an object of type std::allocator<char>, but that can be changed) to allocate and deallocate memory, and the allocator may use a lower-level mechanism again (e.g. variants of operators new and delete) to actually allocate and deallocate. If any of those steps elect to not release memory to the lower-level layer, there is potential impact on heap fragmentation. Commented Sep 25, 2018 at 10:34
  • 2
    If you need to guarantee this behaviour, you can always used your own custom allocator Commented Sep 25, 2018 at 12:26
  • 11
    In my own experience, if I have to utter the phrase "I'm dependent on avoiding heap fragmentation," its a very good time to start considering identifying precise low level requirements, and potentially rolling your own allocation routines. Commented Sep 25, 2018 at 18:06