Why is std::streamsize defined as signed rather than unsigned?

依然范特西╮ 提交于 2020-11-30 07:56:19

问题


According to 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.

As far as I can imagine, a stream's size can never be negative, so, my question is:

Why is std::streamsize defined as signed rather than unsigned? What's the rationale behind?


回答1:


The draft C++ standard has the following footnote 296 in section 27.5.2 Types which says:

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

and we can see in section D.7.1.1 strstreambuf constructors we have the following entries (emphasis mine going forward):

strstreambuf(char* gnext_arg, streamsize n, char *pbeg_arg = 0);
strstreambuf(signed char* gnext_arg, streamsize n,
   signed char *pbeg_arg = 0);
strstreambuf(unsigned char* gnext_arg, streamsize n,
   unsigned char *pbeg_arg = 0);

and says:

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

and we can see from the following discussion that n which is of type streamsize is indeed required to be able to take on a negative value:

— If n > 0, N is n.

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

If n < 0, N is INT_MAX.336

This seems like a poor argument for this requirement and the closed issue 255 has a similar comment from Howard Hinnant which says:

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.



来源:https://stackoverflow.com/questions/24482028/why-is-stdstreamsize-defined-as-signed-rather-than-unsigned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!