为什么data()和c_str()返回char const*,而operator[]返回char&?

为什么 std::string::datastd::string::c_str() 返回指向 const 字符的指针,而std::string::operator[] 返回对 mutable 字符的引用?

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

std::string::data()std::string::c_str() 为什么不返回 char*,或者为什么 std::string::operator[] 不返回 char const&?

Why don’t std::string::data() and std::string::c_str() return char*, or why doesn’t std::string::operator[] return char const&?

这背后的原理是什么?

推荐答案

operator [] 让您可以直接访问 std::string 对象的受控序列.c_str() 原来没有.

operator [] gives you direct access to the controlled sequence of std::string object. c_str() originally did not.

std::string 的原始规范中,存储的序列不需要是一个以零结尾的字符串.这意味着在一般情况下 c_str() 无法返回指向存储序列的直接指针.它必须返回一个指向完全独立、单独分配的受控序列临时副本的指针(添加了零终止符).因此,尝试修改 c_str() 返回的 C 字符串毫无意义.应用于该单独 C 字符串的任何修改都不会传播到实际的受控序列.(事实上??,规范明确禁止任何修改尝试.例如,对于空 std::string,实现可以简单地返回指向字符串文字 "" 的指针,这当然是不可修改的,并且可以在所有 std::string 对象之间轻松共享.)因此,让 c_str() 返回 const char *.

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 更改了 c_str() 的内部规范,使其返回指向实际受控序列的直接指针.但是 c_str() 的外部规范保持不变,以使其与旧规范保持一致.

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.

相关文章