Search code examples
c++stringc++11c++03c-str

Difference in c_str function specification between C++03 and C++11


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?


Solution

  • 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.