c++ - 应该使用 size_t 或 ssize_t

标签 c++ unsigned signed size-t

在我的代码中,我不使用 int 或 unsigned int。我只将 size_t 或 ssize_t 用于可移植。例如:

typedef size_t intc;    // (instead of unsigned int)
typedef ssize_t uintc;  // (instead of int)

因为strlenstringvector……都用size_t,所以我一般用size_t。我只在可能为负数时使用 ssize_t

但我发现:

The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.

在书中The C++ Programming Language .

所以我很困惑。我错了吗?为什么 STL 不遵守书上的建议?

最佳答案

ssize_t 用于返回值可以是有效大小或表示错误的负值的函数。 保证至少能够在 [-1, SSIZE_MAX] 范围内存储值(SSIZE_MAX 取决于系统)。

因此,当您要返回以字节为单位的大小时,您应该使用 size_t,而当您要返回以字节为单位的大小或(负)错误值时,您应该使用 ssize_t .

见: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

关于c++ - 应该使用 size_t 或 ssize_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739490/

相关文章:

c# - 找不到入口点

C - 使用 unsigned int 是否只是糟糕的编码实践?

compare - VHDL 无符号向量与整数比较

c# - 在 C# 中将有符号整数与无符号整数相加

c - 使用自己的 getch 函数进行隐式转换警告

c++ - 如何为共享基类并在定义结构之后定义的结构定义复制构造函数

c++ - 为什么重载!运营商需要一个常量返回

c++ - 如何声明只应在特定上下文中使用的数据结构,C++

c++ - 如果我们添加安全的有符号/无符号比较 C/C++,它会破坏语言或现有代码吗?

java - 签名的 jar 抛出 java.lang.reflect.InvocationTargetException