将'\ 0'添加到std :: string时出现意外行为

bay*_*yda 4 c++ string stl

为什么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;
}
Run Code Online (Sandbox Code Playgroud)

为什么它会加0并计算它?它看起来像字符串的完整性,不是吗?但我检查标准,这是正确的行为.

Mat*_*son 6

为什么标准允许遵循?

因为设计C++字符串的人决定应该允许这样的事情.我不确定那些设计C++字符串的团队中是否有人参与其中...但是既然你自己说标准允许它,那就是它的样子,我怀疑它是否会改变.

拥有一个可以包含"任何东西"的字符串有时候很实用.当我不得不解决C样式字符串不能包含零字节的事实时,我可以想到一些实例.除了长C风格的字符串需要很长时间才能找到它的长度之外,C++字符串的主要好处是它们不仅限于"你可以放入它们的内容" - 这在我的书中是件好事.


fat*_*ihk 2

NULchar'\0'是 的结束字符c style string,而不是std::strings。但是,它支持此字符从 const char 指针获取值,以便它可以找到 c 样式字符串的结尾。否则,它会像其他字符一样被对待