Why do data() and c_str() return char const*, while operator[] returns char&?
c++, constants, software-design, string
Solution
`operator []` gives you direct access to the controlled sequence of `std::string` object. `c_str()` originally did not.
In the original specification of `std::string` the stored sequence was not required to be a zero-terminated string. This meant that in general case `c_str()` could not return a direct pointer to the stored sequence. It had to return a pointer to a completely independent, separately allocated temporary copy of the controlled sequence (with an added zero terminator character). For this reason, trying to modify the C-string returned by `c_str()` made no sense at all. Any modifications applied to that separate C-string would not be propagated to the actual controlled sequence. (In fact, the specification explicitly prohibited any modification attempts. For example, for an empty `std::string` an implementation could simply return a pointer to a string literal `""`, which was of course non-modifiable and could be easily shared between all `std::string` objects.) So, it made perfect sense to make `c_str()` to return `const char *`.
C++11 changed the internal specification of `c_str()` making it to return a direct pointer to the actual controlled sequence. But the external spec of `c_str()` remained unchanged to keep it aligned with the legacy spec.
Problem
Why do `std::string::data` and `std::string::c_str()` return pointers to const chars, while `std::string::operator[]` returns references to mutable chars? ``` std::string string("eightfold is the greatest"); auto s = string.data(); *s = 'r'; // illegal auto t = &string[0]; *t = 'r'; // totally fine auto& c = string[0]; c = 'r'; // totally fine ``` Why don’t `std::string::data()` and `std::string::c_str()` return `char*`, or why doesn’t `std::string::operator[]` return `char const&`? What is the rationale behind this?