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

后端 未结 1 1879
囚心锁ツ
囚心锁ツ 2021-02-05 02:38

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 character

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 03:18

    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.

    0 讨论(0)
提交回复
热议问题