1

When using operations like append, concatenation, insert. Does it create new copies of the string? Is any additional memory consumed while doing so?

3
  • 2
    Not necessarily. For instance, if you append and there's enough space left in the memory that was allocated for the string (its capacity), it'll just add to the string. If it doesn't fit, however, it will have to reallocate, and that includes copying over the string's memory to the new buffer. The new buffer is usually big enough so you can append some more stuff without having to reallocate again. This is called an amortized constant runtime: appending is O(n) because it may have to reallocate, but appending n little pieces is still O(n), so O(1) per piece.
    – Blaze
    Commented Feb 6, 2020 at 8:58
  • It depends, to some extent, on how you do the operations. Regardless of whether temporary std::strings are created, the working of std::string means that it may reallocate memory - after all, it needs to ensure enough memory is allocated to hold the complete string - but the details are implementation defined.
    – Peter
    Commented Feb 6, 2020 at 9:17
  • @Caleth I think Blaze was talking about a second attempt to append something to the string (in order to avoid to reallocate each time we want to append something). --> "The new buffer is usually big enough so you can append some more stuff without having to reallocate again."
    – Fareanor
    Commented Feb 6, 2020 at 9:57

0

Browse other questions tagged or ask your own question.