“结束”有什么用?这些日子?

发布于 2024-08-23 04:34:36 字数 946 浏览 5 评论 0原文

几天前我遇到了一个微妙的错误,代码看起来像这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无远思近则忧 2024-08-30 04:34:36

您基本上已经回答了您自己的问题,并提供了所需的详细信息。当 std::stringstd::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 when std::string and std::stringstream handle all that for you.

So, to answer your question explicitly, no, there is no reason to use std::ends in a std::string only environment.

(り薆情海 2024-08-30 04:34:36

有些 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文