c++ - 为什么 std::streamsize 被定义为有符号而不是无符号?

标签 c++ iostream language-lawyer unsigned signed

根据http://en.cppreference.com/w/cpp/io/streamsize

The type std::streamsize is a signed integral type used to represent the number of characters transferred in an I/O operation or the size of an I/O buffer.

据我所知,流的大小永远不会是负数,所以,我的问题是:

为什么 std::streamsize 被定义为 signed 而不是 unsigned?背后的原理是什么?

最佳答案

draft C++ standard27.5.2 Types 部分有以下脚注 296 说:

streamsize is used in most places where ISO C would use size_t. Most of the uses of streamsize could use size_t, except for the strstreambuf constructors, which require negative values. It should probably be the signed type corresponding to size_t (which is what Posix.2 calls ssize_t).

我们可以在 D.7.1.1 部分中看到 strstreambuf 构造函数 我们有以下条目(强调我的 future ):

strstreambuf(char* gnext_arg, <b>streamsize n</b>, char *pbeg_arg = 0);
strstreambuf(signed char* gnext_arg, <b>streamsize n</b>,
   signed char *pbeg_arg = 0);
strstreambuf(unsigned char* gnext_arg, <b>streamsize n</b>,
   unsigned char *pbeg_arg = 0);

然后说:

gnext_arg shall point to the first element of an array object whose number of elements N is determined as follows:

从下面的讨论中我们可以看出,类型为streamsizen确实需要能够取负值:

— If n > 0, N is n.

— If n == 0, N is std::strlen(gnext_arg).

If n < 0, N is INT_MAX.336

对于这个要求和 closed issue 255 来说,这似乎是一个糟糕的论据。 Howard Hinnant 也有类似的评论:

This is something of a nit, but I'm wondering if streamoff wouldn't be a better choice than streamsize. The argument to pbump and gbump MUST be signed. [...] This seems a little weak for the argument to pbump and gbump. Should we ever really get rid of strstream, this footnote might go with it, along with the reason to make streamsize signed.

关于c++ - 为什么 std::streamsize 被定义为有符号而不是无符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24482028/

相关文章:

c++ - 非类型模板参数中的C++类类型:推导指南失败

c++ - 对称正定矩阵的特征有效逆

c++ - 使用c++程序控制linux终端

c++ - 使用帧指针优化进行调试

c++ - 对 `std::istreambuf_iterator` 的用法感到困惑

c++ - 当 std::stringstream 使用 ("some content"构造时,tellg() 的预期行为是什么,std::ios::in|std::ios::ate)?

c++ - 使用 fstream C++ 读取字节

c++ - 也许我对 [class.access]/7 的理解不正确,但是

C 数组声明符

c++ - 是使用引入一个新的成员函数还是只是一个别名?