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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…