这些天有什么用来“结束”? [英] What use is there for 'ends' these days?

查看:147
本文介绍了这些天有什么用来“结束”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

问题是结束 a'\0'到 ostringstream 所以 theWholeLot 实际上看起来像7HABITS \ 0(即在结尾处为空)

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)

现在这没有显示,因为 theWholeLot 然后被用来使用 string :: c_str()使用 const char * null被屏蔽,因为它只是一个分隔符。然而,当这改变为使用字符串整个,null突然意味着某事和比较如:

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" )

将失败。这让我想到:假设结束的原因是当流不​​正常时对 ostrstream 的回溯以 str()(然后它不是一个 string code> char * )将正常工作。

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.

任何人都可以看到使用结束的明显原因 std :: string 只有环境中?

Can anyone see an obvious reason to use ends in a std::string only environment?

推荐答案

基本上回答了你自己的问题是所需要的细节。我当然不能想到任何理由使用 std :: ends std :: string std :: stringstream 处理所有这些。

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.

因此,为了明确回答你的问题,在 std :: string 环境中使用 std :: ends

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

这篇关于这些天有什么用来“结束”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆