Std :: string :: c_str & null termination

I read various descriptions std::string::c_str, including questions raised by SO over years / decades,

I like this description for its clarity:

Returns a pointer to an array that contains a zero-terminated sequence of characters (i.e., a C-string) representing the current value of a string object. This array contains the same sequence of characters that make up the value of the string object plus an additional terminating null character ('\ 0') at the end.

However, some things about the purpose of this feature are still unclear.

You can forgive me for thinking that the call c_strcan add a character \0to the end of the string, which is stored in the char array of the host object ( std::string):

s[s.size+1] = '\0'

But it seems that std::stringNull objects are completed by default even before the call c_str: enter image description here

Having looked at the definition:

const _Elem *c_str() const _NOEXCEPT
{   // return pointer to null-terminated nonmutable array
    return (this->_Myptr());
}

I do not see any code that would add \0to the end of the char array. As far as I can tell, it c_strjust returns a pointer to a char stored in the first element of the array, pretty much like begin(). I don’t even see the code that checks that the internal array is complete\0

Or am I missing something?

+4
source share
3 answers

++ 11 , a std::string ( std::basic_string), std::string ) '\0'. - data() c_str() - data() ( '\0' c_str(), '\0'. , , '\0' ( undefined)..... , , '\0'.

++ 11 . , - data() , c_str() (.. '\0'). , '\0' , data(), , , .

, , , ++ 11 - trailing '\0' (.. , , -, , , ).

, , ++ ++ 11. , std::string , ++ 11 '\0', , , .

+4

, '\0' , . c_str , std::string.

, :

  • '\0' _Myptr()
  • , '\0', c_str(), .

_Myptr() c_str() . std::string, .

+6

c_str cstring . , , . ( , , ) , . ,

std::string s;
assert(s[0] == '\0');

, string[string.size()]. , [] , , size() \0.

+1
source

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


All Articles