I've read various descriptions of std::string::c_str
including questions raised on SO over the years/decades,
I like this description for its clarity:
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. This array includes 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 function are still unclear.
You could be forgiven for thinking that calling c_str
might add a \0
character to the end of the string which is stored in the internal char array of the host object (std::string
):
s[s.size+1] = '\0'
But it seems std::string
objects are Null terminated by default even before calling c_str
:
After looking through the definition:
const _Elem *c_str() const _NOEXCEPT
{ // return pointer to null-terminated nonmutable array
return (this->_Myptr());
}
I don't see any code which would add \0
to the end of a char array. As far as I can tell c_str
just returns a pointer to the char stored in the first element of the array pretty much like begin()
does. I don't even see code which checks that the internal array is terminated by \0
Or am I missing something?