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.
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.
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.
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).
While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With