gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:51:51 31 4
gpt4 key购买 nike

根据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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com