“结束”有什么用?这些日子?
几天前我遇到了一个微妙的错误,代码看起来像这样:
ostringstream ss;
int anInt( 7 );
ss << anInt << "HABITS";
ss << ends;
string theWholeLot = ss.str();
问题是 ends
将 '\0' 粘贴到 ostringstream
中,所以theWholeLot
实际上看起来像 "7HABITS\0"
(即末尾为空)
现在这还没有出现,因为 theWholeLot
当时正在用于使用 string::c_str()
获取 const char *
部分,这意味着 null 被屏蔽,因为它只是一个分隔符。然而,当整个过程改为使用字符串时,null 突然意味着某些内容,并且诸如: 之类的比较
if ( theWholeLot == "7HABITS" )
将失败。这让我开始思考:大概 ends
的原因是对 ostrstream
时代的回溯,当时流通常不会以 null 终止,并且必须这样 >str()
(然后抛出的不是 string
而是 char *
)将正常工作。
然而,现在不可能从 ostringstream
中转换出 char *
,使用 ends
不仅是多余的,而且有潜在的危险,我正在考虑将它们全部从我的客户代码中删除。
任何人都可以看到在仅 std::string
环境中使用 ends
的明显原因吗?
I came across a subtle bug a couple of days ago where the code looked something like this:
ostringstream ss;
int anInt( 7 );
ss << anInt << "HABITS";
ss << ends;
string theWholeLot = ss.str();
The problem was that the ends
was sticking a '\0' into the ostringstream
so theWholeLot
actually looked like "7HABITS\0"
(i.e. a null at the end)
Now this hadn't shown up because theWholeLot
was then being used to take the const char *
portion using string::c_str()
That meant that the null was masked as it became just a delimiter. However, when this changed to use strings throughout, the null suddenly meant something and comparisons such as:
if ( theWholeLot == "7HABITS" )
would fail. This got me thinking: Presumably the reason for ends
is a throwback to the days of ostrstream
when the stream was not normally terminated with a null and had to be so that str()
(which then cast out not a string
but a char *
) would work correctly.
However, now that it's not possible to cast out a char *
from a ostringstream
, using ends
is not only superfluous, but potentially dangerous and I'm considering removing them all from my clients code.
Can anyone see an obvious reason to use ends
in a std::string
only environment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您基本上已经回答了您自己的问题,并提供了所需的详细信息。当
std::string
和std::stringstream
处理所有这些时,我当然想不出任何理由使用std::ends
你。因此,要明确回答您的问题,不,没有理由在仅
std::string
环境中使用std::ends
。You've essentially answered your own question is as much detail that's needed. I certainly can't think of any reason to use
std::ends
whenstd::string
andstd::stringstream
handle all that for you.So, to answer your question explicitly, no, there is no reason to use
std::ends
in astd::string
only environment.有些 API 需要一个包含多个以零结尾的字符串的“字符串数组”,用双零来标记结尾。 Raymond Chang 最近发表了有关此内容的博客,最重要的是来证明这一点被搞砸的频率。
There are some APIs that expect a "string array" with multiple zero terminated strings, a double zero to mark the end. Raymond Chang just recently blogged about it, most of all to demonstrate how often that this gets fumbled.