<分区>
先从标准中摘录一些:
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 thatp + 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
个元素。)