Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The benefits of std::string not storing the data in a contiguous memory location (pre C++11)

Tags:

c++

string

memory

In C++98 and C++03 std::string could have stored it's underling data in a non-contiguous memory. What was the reason for this? What possible optimization could have been achieved by this relaxed requirement? Did any compiler/architecture actually make use of this?

If you have parts of the string stored in different memory locations, wouldn't the iterator be overly complicated? And the class too, as it would need to know exactly where different parts of the string are.

like image 532
bolov Avatar asked Dec 08 '15 12:12

bolov


People also ask

Is std::string contiguous?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array.

Why std::string?

The full name of string is std::string because it resides in namespace std , the namespace in which all of the C++ standard library functions, classes, and objects reside.

How are strings stored C++?

In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).

Does std::string allocate?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.


1 Answers

The chief reason was that string concatenation could take place without re-allocation. I believe that early versions of STLPort exploited this.

Another reason is that it was possible to implement copy-on-write or even partial copy-on-write. Although other requirements demanded of std::string (especially the move semantics of C++11) now mean this is no longer possible.

like image 70
Bathsheba Avatar answered Oct 05 '22 23:10

Bathsheba