将 std::string 和 std::string::c_str() 放入字符串流有什么区别?
我们看到一个奇怪的场景,基本上可以归结为以下内容:
std::string something = "someval";
std::stringstream s;
s << something;
std::cout << s.str();
不等于:
std::string something = "someval";
std::stringstream s;
s << something.c_str();
std::cout << s.str();
更进一步 - 在任何一种情况下,输出都不是乱码。发生的情况是,情况 1 的输出似乎映射到系统中的另一个(有效)字符串,而情况 2 的输出是预期的。
我们通过简单地更改:
s << something;
到:
s << something.c_str();
我知道这听起来很疯狂(或者对我来说确实如此),并且我无法将其复制到更大的系统中 - 很抱歉没有“有效”的示例。但有谁知道这种事情怎么会发生呢?我们可以在某个地方踩到内存或者对某个位置的字符串表做一些事情或者其他类似的事情吗?
We're seeing a strange scenario that basically boils down to the following:
std::string something = "someval";
std::stringstream s;
s << something;
std::cout << s.str();
is not equal to:
std::string something = "someval";
std::stringstream s;
s << something.c_str();
std::cout << s.str();
Taking that a step farther - the output is not gibberish in either case. What is happening is the output from case 1 appears to be mapped to another (valid) string in the system whereas the output from case 2 is what is expected.
We see this behavior by simply changing:
s << something;
To:
s << something.c_str();
I know this sounds crazy (or it does to me), and I haven't been able to replicate it out of the larger system - so sorry for no "working" example. But does anyone know how this kind of thing can happen? Can we be stepping on memory somewhere or doing something to a stringtable in some location or anything else like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果字符串包含空字符,
'\0'
,情况会有所不同。.c_str() 版本将计算直到 nul 的长度,而 std::string 输出将知道其长度并输出其所有字符。
It is different if the string contains nul characters,
'\0'
.The .c_str() version will compute the length up to the nul, while the std::string output will know its length and output all its characters.