How are C ++ strings stored?

Possible duplicate:
std :: string and its automatic memory resizing

I'm just wondering how the lines are 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 line, it works, but I don’t understand how to do it. For example, I do this:

 testString = "123456789" 

Now it should be 10 bytes. But what if there was no room for such a line? let's say that the fifth + sixth byte from the beginning of the line takes some other 2 characters. How does the processor handle it? He finds a completely new position in memory, where does this line fit?

+7
source share
4 answers

It depends on the implementation, but the general idea is that the string class will contain a pointer to the memory area in which the actual contents of the string are stored. In two general implementations, 3 pointers are stored (the beginning of the selected area and data, the end of the data, the end of the selected area) or a pointer (the beginning of the selected area and data) and two integers (the number of characters per line and the number of bytes allocated).

When new data is added to the line, if it corresponds to the selected area, it will simply be written, and accordingly the pointer to the size / end of the pointer will be updated. If the data does not correspond to the region, a new buffer will be created and the data will be copied.

Also note that in many implementations there are optimizations for small strings, where the string class contains a small buffer. If the contents of the string fit into the buffer, then the memory is not allocated dynamically and only the local buffer is used.

+12
source

string not a simple data type, such as char * . This is a class that has implementation details that are not necessarily visible.

Among other things, string contains a counter to track how large it is.

 char[] test = "asd"; // allocates exactly 4 bytes string testString = "asd"; // who knows? testString = "longer"; // allocates more if necessary 

Suggestion: write a simple program and go through it with a debugger. Examine string and see how private members change as the value changes.

+3
source

string is an object, not just some memory cell. It dynamically allocates memory as needed.

Operator = Overloaded; when you say testString = "123456789"; , the method is called and processes the const char * that you passed.

+2
source

It is stored with size. If you save a new line, it will not necessarily free up existing memory and allocate new memory to handle resizing.

And it does not necessarily allocate 4 bytes when it is first assigned to a string of 4 bytes. He can allocate more space than this (he will not allocate less).

+2
source

All Articles