In the C++ reference of c_str()
in std::string
the following appears:
Return value
Pointer to the underlying character storage.data()[i] == operator[](i) for every i in [0, size())
(until C++11)data() + i == &operator[](i) for every i in [0, size()]
(since C++11)
I do not understand the difference between the two, except for the range increase by one element since C++11.
Isn't the former statement data()[i] == operator[](i)
also true for the latter?
The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).
The function c_str() is, once again, a member function of the string class that returns a c-string or ntca with the data equivalent to the name entered by the user. In other words, filename. c_str() is a c-string (or ntca).
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.
The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated. Note that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.
Except for the range increment by one element since C++11, there is still a big difference between:
data()[i] == operator[](i)
and:
data() + i == &operator[](i)
That main difference is the &
operator in the prototypes.
The old prototype, allowed for copy to be made when a write operation would occur, since the pointer returned could point to another buffer than the one holding the original string.
The other difference in the prototypes between data()[i]
and data() + i
, is not critical, since they are equivalent.
A difference between C++ and C++11 is that in the former, an std::string
was not specified explicitly by the standard for whether it would have a null terminator or not. In the latter however, this is specified.
In other words: Will std::string always be null-terminated in C++11? Yes.
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