Possible Duplicate:
std::string and its automatic memory resizing
I am just curious, how are strings stored in memory? for example, when I do this:
string testString = "asd";
it allocates 4 bytes, right? a + s + d + \0.
But later, when I want to assign some new text to this string, it works, but I don’t understand how. For example I do this:
testString = "123456789"
Now it should be 10 bytes long. But what if there wasn’t space for such string? let’s say that fifth+sixth bytes from the beginning of string are taken by some other 2 chars. How does the CPU handles it? It finds completely new position in memory where that string fits?
This is implementation dependent, but the general idea is that the string class will contain a pointer to a region of memory where the actual contents of the string are stored. Two common implementations are storing 3 pointers (begin of the allocated region and data, end of data, end of allocated region) or a pointer (begin of allocated region and data) and two integers (number of characters in the string and number of allocated bytes).
When new data is appended to the string, if it fits the allocated region it will just be written and the size/end of data pointer will be updated accordingly. If the data does not fit in the region a new buffer will be created and the data copied.
Also note that many implementations have optimizations for small strings, where the string class does contain a small buffer. If the contents of the string fit in the buffer, then no memory is dynamically allocated and only the local buffer is used.