为什么data()和c_str()返回char const *,而operator []返回char&amp ;? [英] Why do data() and c_str() return char const*, while operator[] returns char&?

查看:99
本文介绍了为什么data()和c_str()返回char const *,而operator []返回char&amp ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 std :: string :: data std :: string :: c_str()为什么返回指针到 const 字符,而 std :: string :: operator [] 返回对可变字符的引用?

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 * ,或为什么 cstd :: 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 ,实现可以简单地返回指向字符串文字<$ c $的指针。 c> ,这当然是不可修改的,可以很容易地在所有 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.

这篇关于为什么data()和c_str()返回char const *,而operator []返回char&amp ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆