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?
c_str()
doesn't append a 0 at the end of the array every time it is called, because it would need to allocate a new array, and the caller (presumably you) would need to deallocate it every time and again... – Trilemmac_str
is markedconst
this means according to the current language in the standard that it should be, relatively speaking, data race free. If you modify the string in aconst
method you would have to lock because you need to verify the values hasn't changed. The standard requires thatc_str
is also O(1) which in essence means that the internal representation must be zero terminated. – Iridium