One thing I'm not pretty sure after googling for a while, is the returned string of getline(). Hope to get it confirmed here.
std::getline
This global version returns a std::string so it's not necessarily null-terminated. Some compilers may append a '\0' while the others won't.
std::istream::getline
This function returns a c-style string so it's guaranteed that the string is null-terminated.
Is that right?
Null termination is a concept that is applicable only to C strings; it does not apply to objects of std::string
- they let you find the size by calling size()
, and do not require null termination. However, strings returned from std::string
's c_str()
function are null terminated, regardless of where the data for the string came from.
C++11 standard describes the prerequisites of the operator [pos]
in the section 21.4.5.2:
Returns:
*(begin() + pos)
ifpos < size()
. Otherwise, returns a reference to an object of typecharT
with valuecharT()
, where modifying the object leads to undefined behavior.
Note the pos < size()
, as opposed to pos <= size()
: the standard explicitly allows std::string
objects not to have null termination.
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