String’s static memory vs dynamic memory?


Nephi Immortal

string class has four data members: proxy class, buffer, size, and capacity.. The buffer has fixed 16 elements. It is stored into stack. If you insert between 1 and 16 characters into string’s buffer, the buffer with fixed 16 elements is filled. If you insert more than 16 characters, 4 elementsout of 16 elements in the buffer is replaced with pointer to char or char*before new buffer is allocated into heap.

What happen if you delete all the characters or leave one character in the buffer? The buffer in the heap will be reallocated to 32 elements in heap or deallocated before memory address in the buffer with fixed 16 elements will be overwritten to store between 1 and 16 characters.

The basic_string source code of Microsoft looks weird and is so confusing. Do advanced programmers read and understand it?

Reminder: overwritten buffer may be possible to overwrite other data members in memory. It is considered unsafe. I have seen across several websites.. Some programmers don't like Microsoft's code so that they write their own string class.




+1 for Paavo. I see nothing wrong with the way the code works, it is a +/- classic string implementation with short string optimization.

You should note, however, that this is but one implementation. C++ standarddoes not demand that std::string works that way, and inded, you will also find reference counted/copy on write implementations, you will find implementations that allocate bigger buffer in hope to avoid some reallocations, and you will also find string implementations with no optimization at all.

As for "do people read this", I do, occasionally, and I would guess others do it, too. I also pass the code through the debugger - to me, there's nothing better to understanding, than seeing the code unfold at runtime. Finally, standard library implemantation code often uses coding conventions different from yours/mine, which also makes the code look strange. But given that there's so many conventions to choose from, that's inevitable ;-).


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question