Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 606
Chiel Avatar asked Aug 20 '17 12:08

Chiel


People also ask

What does c_str () mean in C++?

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

What does filename c_str () mean?

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

Where is c_str defined?

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.

What type does c_str return?

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.


1 Answers

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.

like image 70
gsamaras Avatar answered Oct 12 '22 06:10

gsamaras