In C++11 basic_string::c_str
is defined to be exactly the same as basic_string::data
, which is in turn defined to be exactly the same as *(begin() + n)
and *(&*begin() + n)
(when 0 <= n < size()
).
I cannot find anything that requires the string to always have a null character at its end.
Does this mean that c_str()
is no longer guaranteed to produce a null-terminated string?
c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.
Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .
No. Since c_str returns a pointer p to a null-terminated array of characters, there must be some value i >= 0 such that p[i] == '\0' , and thus p cannot be null.
In C the strings are basically array of characters. In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0').
Strings are now required to use null-terminated buffers internally. Look at the definition of operator[]
(21.4.5):
Requires:
pos <= size()
.Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeT
with valuecharT()
; the referenced value shall not be modified.
Looking back at c_str
(21.4.7.1/1), we see that it is defined in terms of operator[]
:
Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
in[0,size()]
.
And both c_str
and data
are required to be O(1), so the implementation is effectively forced to use null-terminated buffers.
Additionally, as David Rodríguez - dribeas points out in the comments, the return value requirement also means that you can use &operator[](0)
as a synonym for c_str()
, so the terminating null character must lie in the same buffer (since *(p + size())
must be equal to charT()
); this also means that even if the terminator is initialised lazily, it's not possible to observe the buffer in the intermediate state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With