@SethCarnegie is right: more than one implementation is possible. The C ++ standard does not indicate which one should be used.
However, the question is still interesting. This is a classic computer science problem. Where and how, does memory allocate when it is not known in advance how much memory is allocated?
One solution is to write string characters as a linked list of individual characters. It is not memory efficient and not fast, but it works, is reliable and relatively easy to program. However, the standard library is unlikely to be implemented in this way.
The second solution is to allocate a buffer of a certain fixed length, for example 128 characters. When the buffer is full, you allocate a new double-length buffer, 256 characters, then copy the old characters to the new storage, and then release the old one. When the new buffer overflows, you again add an even newer buffer of double length, 512 characters, and then repeat the process; etc.
The third solution combines the first two. A linked list of character arrays is supported. The first two members of the list store (say) 128 characters each. Third store 256. Fourth store 512 and so on. This requires more programs than others, but may be preferable either depending on the application.
And the list of possible implementations continues.
Regarding standard library implementations, @SteveJessop adds that the standard library string [a] cannot be implemented as (1) due to the complexity of operator[] for strings. In C ++ 11, this is (3) either because of the adjacency requirement for strings. The C ++ Committee was convinced that no active implementation in C ++ was being executed (3) at the time when they added the contact requirement. Of course, getline can do what it likes temporarily with characters before adding them to a string, but the standard really says a lot about what a string can do. "
Adding is relevant, because although getline can temporarily store its data in any of several ways, if the final goal of the data is a string, this may be related to the implementation of getline . @SteveJessop further adds: "For the string itself, implementations pretty much need to be (2), except that they can choose their own expansion speed, they don't need to double each time they are multiplied by some constant."
source share