Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

c++ - Why do data() and c_str() return char const*, while operator[] returns char&?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...