c++ - C++1 1's std::string' 的底层表示是否保证有终止空字符?

标签 c++ string c++11

<分区>

先从标准中摘录一些:

string::operator[]() 规范:

const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Requires: pos <= size().
Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.
Complexity: constant time.

string::c_str()string::data() 规范:

const charT* c_str() const noexcept;
const charT* data() const noexcept;
Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].
Complexity: constant time.

通过结合这两个规范,我们可以看到 c_str()/data() 返回的指针 p 必须满足 p[0...size()-1]指定字符串的元素,p[size()]等于operator[](size( )),它指定一个具有值 charT() 的对象。由于指针上的加法运算符用于获取字符串元素和最后一个 charT() 对象的地址,因此它们必须位于单个数组中(您不能只放置字符串元素并即时创建一个 charT() 对象并返回它)。那么可以肯定地说,在 C++11 中,str::string 保证在其底层存储中包含终止空字符吗?


编辑:我为未能注意到我的问题而道歉,这是一个重复的问题。但是,我在这里得到的答案似乎与那个重复问题中的答案相冲突。

此外,我应该像这样削弱我的假设:std::string 的底层表示应该保留足够的空间来保存终止空字符,并自由设置 charT() 值,直到 c_str()/data() 被调用。 (即底层存储必须能够在任何时候至少容纳 size()+1 个元素。)

最佳答案

不,不是。 std::string 可以延迟计算 c_str()data() 所需的结果。在调用这些方法之前,无法保证空终止符存在于底层存储中。

标准只保证字符串字符的连续性。

关于c++ - C++1 1's std::string' 的底层表示是否保证有终止空字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22328442/

相关文章:

c++ - 用于参数包扩展的 "pattern"的定义,尤其是在函数调用中

c++ - 如何从 SQLite 数据库中读取数据?

C++——DirectWrite : Load font from file at runtime

c++ - 为什么 Microsoft Visual Studio 找不到 <stdint.h>?

初始化新对象时的C++默认构造函数和POD问题

linux - Linux Shell 脚本问题

c# - 使用开始和结束标记分割字符串

c++ - ".exe has stopped working"当我尝试计算字符串时

c++ - 为什么在派生类c++中找不到基类成员

c++ - 使用 boost 序列化到磁盘后无法加载回数据