gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:24 25 4
gpt4 key购买 nike

为什么 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算呢?它看起来像是破坏了字符串的完整性,不是吗?但我检查了标准,这是正确的行为。

最佳答案

Why does standard allows following?

因为设计 C++ 字符串的人决定允许这样的事情发生。我不确定设计 C++ 字符串的团队中是否有人在 SO 上……但是既然你自己说标准允许它,那就是它的方式,我怀疑它是否会改变。

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

关于c++ - 将 '\0' 添加到 std::string 时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17403066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com