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?
The type std::streamsize is an implementation-defined signed integral type used to represent the number of characters transferred in an I/O operation or the size of an I/O buffer. It is used as a signed counterpart of std::size_t, similar to the POSIX type ssize_t .
gcc actually defines size_t as a signed integer type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With