We all know there is a null character automatically attached to the end of a C-string...How about C++ string object? Is there also a null character at the end of it?
Thank you so much!
We all know there is a null character automatically attached to the end of a C-string...How about C++ string object? Is there also a null character at the end of it?
Thank you so much!
In C++03, a std::string was not required to be stored in a NUL-terminated buffer, but if you called c_str()
it would return a pointer to a NUL-terminated buffer. That buffer could legally be created and/or terminated inside the c_str()
call.
In C++11, all std::string
instances are terminated, so data()
also addresses a NUL-terminated buffer, and even s[s.size()]
has a well-defined meaning returning a reference to the terminating NUL.
std::string
is very much a std::vector
: it has a length attribute and is not zero terminated in C++03; in C++11 'std::string' does seems to be terminated, but I find it easier to think of 'std::string' as a 'std::vector' of characters and not just a terminated buffer.
std::string::data
Returns a pointer to an array that contains the same sequence of characters as the characters that make up the value of the string object.
Accessing the value at data()+size() produces undefined behavior: There are no guarantees that a null character terminates the character sequence pointed by the value returned by this function. See string::c_str for a function that provides such guarantee.
A program shall not alter any of the characters in this sequence.