Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...