我一直想知道为什么 C++ 标准库使用 char
类型而不是 unsigned char
类型来实例化 basic_[io]stream 及其所有变体.char
意味着(取决于它是否有符号)你可以有像 get() 这样的操作的上溢和下溢,这将导致所涉及的变量的实现定义的值.另一个例子是当你想使用 put
函数将一个未格式化的字节输出到 ostream 时.
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.
有什么想法吗?
注意:我还是不太相信.所以如果你知道最终答案,你仍然可以发布它.
Note: I'm still not really convinced. So if you know the definitive answer, you can still post it indeed.
可能我误解了这个问题,但是从 unsigned char 到 char 的转换不是未指定的,它依赖于实现(C++ 标准中的 4.7-3).
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).
C++ 中 1 字节字符的类型是char",而不是unsigned char".这为实现在平台上做最好的事情提供了更多的自由(例如,标准机构可能认为存在有符号字节算术比无符号字节算术更快的 CPU,尽管这是我的推测).也是为了与 C 兼容.从 C++ 中消除这种存在不确定性的结果是 C# ;-)
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# ;-)
鉴于存在char"类型,我认为即使未定义其符号性,通常的流也可以使用它.因此,也许您的问题可以通过为什么 C++ 不将 char 定义为无符号?"的答案来回答?
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!