I always thought an std::string was implemented as an STL wrapper for a C char array string. But looking closely at the design, I’ve noticed that it doesn’t give any hint or sign of being a wrapped up c-string. For all I know an std::string could be doing anything internally!
There is the c_str() method of course which I thought returned the internal char array, but how do I know if the method doesn’t create a new c char array from whatever data it stores inside and return it?
Seriously, how has std::string been implemented? Is it (as it appears to be) just a wrapper for a C char array, or is it something else? Or a mixture of the two? Or even can become both conditionally?
For all you know. The standard, of course, describes and demands certain semantics that rule anything out. It says the following on the
basic_stringtemplate:§21.4 [basic.string] p1And a “char-like object” is defined by the following text:
§21.1 [strings.general] p1This effectively means that you can stuff anything you want into
basic_string, as long as it’s not an array and it is a POD (see this and this for infos on what PODs are). These char-like objects are then manipulated with the help of character traits, which define the specific behaviour of and relationship between them.In C++03 exactly this was possible to do for the implementation, a known defect that has since been corrected in C++11:
§2.4.1 [string.require] p5See also these related questions: