【发布时间】:2013-07-01 11:09:58
【问题描述】:
为什么 C++ 标准允许以下内容?
#include <iostream>
#include <string>
int main()
{
std::string s(10, '\0'); // s.length() now is 10
std::cout << "string is " << s << ", length is " << s.length() << std::endl;
s.append(5, '\0'); // s.length() now is 15
std::cout << "string is " << s << ", length is " << s.length() << std::endl;
// the same with += char and push_back
// but:
s += "hello"; // s.length() returns 20 string is "hello"
std::cout << "string is " << s << ", length is " << s.length() << std::endl;
return 0;
}
为什么要加0并计数呢? 看起来字符串的完整性被破坏了,不是吗?但我检查了标准,这是正确的行为。
【问题讨论】:
-
std::string不是以 null 结尾的字符串。 -
“字符串完整性受损”?
std::string的全部意义在于,您不受 1970 年以来的任意限制,例如“不能包含\0”。 -
如果您检查了标准并发现这是正确的行为,您的问题是什么?
-
将
std::string视为一种字符容器,其中包含一堆字符串功能。 -
+= "hello"行之后,该字符串不是 5 个字符的字符串"hello",正如您的评论所暗示的那样。该字符串实际上是"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0hello",但您的终端可能无法打印 ASCII NUL 字符,因此它似乎只打印"hello"。但是,如果您将程序的输出保存到一个文件并检查原始文件数据,您会在其中看到 15 个 NUL 字符。