Does std :: string really complete a C char array?

I always thought that std::string was implemented as an STL wrapper for a string of C char array. But, looking at the design, I noticed that it does not give any hints or signs that you are wrapped in a c-string. As far as I know, std::string can do something internally!

There is, of course, the c_str() method, which, as I thought, returned the internal char array, but how do I know if the method creates a new c char array from any data that it stores inside and returns It?

Seriously, how is std::string implemented? Is this (as it seems) just a wrapper for a C char array, or is it something else? Or a mixture of the two? Or can it even become conditional?
+4
source share
1 answer

As far as I know, std :: string can do something internally!

All that you know. The standard, of course, describes and requires a certain semantics that does not tolerate anything. The following is specified in the basic_string pattern:

Β§21.4 [basic.string] p1

The template of the basic_string class describes objects that can store a sequence consisting of a different number of arbitrary char-like objects with the first element of the sequence at the zero position. Such a sequence is also called a "string" if the type of char objects that it holds are clear from the context. In the rest of this section, the type of char-like objects stored in the basic_string object is denoted by charT .

And a "char-like object" is defined by the following text:

Β§21.1 [strings.general] p1

This section describes the components for managing sequences of any type of POD array (3.9). In this section, such types are called char-like types, and char type objects are called char-like objects or simply characters.

This actually means that you can embed anything you want into basic_string if it is not an array, but a POD (see this and this for information on what POD is). These char-like objects are then processed using character traits that define the specific behavior and relationships between them.


[...], but how do you know if a method creates a new array of c char from any data stored inside and returns it?

In C ++ 03, this is exactly what could be done for implementation, a known defect that has since been fixed in C ++ 11:

Β§2.4.1 [string.require] p5

The char objects in the basic_string object must be stored contiguously. That is, for any basic_string s object, the identifier &*(s.begin() + n) == &*s.begin() + n will be executed for all n values ​​such that 0 <= n < s.size() .

See also the following questions:

+12
source

Source: https://habr.com/ru/post/1401098/


All Articles