为什么C ++流使用char而不是unsigned char? [英] Why do C++ streams use char instead of unsigned char?

查看:215
本文介绍了为什么C ++流使用char而不是unsigned char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么C ++标准库使用 char 类型而不是实例化basic_ [io] unsigned char 类型。 char 意味着(取决于它是否被签名),可以有像get()这样的操作的溢出和下溢,这将导致涉及的变量的实现定义的值。另一个例子是当你想使用 put 函数输出一个未格式化的字节到ostream。



Any

真的说服了。

解决方案

可能我误解了这个问题,但是转换从unsigned char到char不是未指定的,它是与实现相关的(在C ++标准中是4.7-3)。



C ++中的1字节字符的类型是char,而不是unsigned char。这使得实现在平台上做最好的事情有点自由(例如,标准机构可能相信存在有符号字节算术比无符号字节算术更快的CPU,尽管这是我的推测)。也是为了与C的兼容性。从C ++中消除这种存在不确定性的结果是C#; - )



由于char类型存在,我认为感觉通常流使用它,即使它的signedness没有定义。所以也许你的问题是由答案,为什么C ++只是定义char是无符号?回答。


I've always wondered why the C++ Standard library has instantiated basic_[io]stream and all its variants using the char type instead of the unsigned char type. char means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-defined value of the variables involved. Another example is when you want to output a byte, unformatted, to an ostream using its put function.

Any ideas?


Note: I'm still not really convinced. So if you know the definitive answer, you can still post it indeed.

解决方案

Possibly I've misunderstood the question, but conversion from unsigned char to char isn't unspecified, it's implementation-dependent (4.7-3 in the C++ standard).

The type of a 1-byte character in C++ is "char", not "unsigned char". This gives implementations a bit more freedom to do the best thing on the platform (for example, the standards body may have believed that there exist CPUs where signed byte arithmetic is faster than unsigned byte arithmetic, although that's speculation on my part). Also for compatibility with C. The result of removing this kind of existential uncertainty from C++ is C# ;-)

Given that the "char" type exists, I think it makes sense for the usual streams to use it even though its signedness isn't defined. So maybe your question is answered by the answer to, "why didn't C++ just define char to be unsigned?"

这篇关于为什么C ++流使用char而不是unsigned char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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