gpt4 book ai didi

c++ - 应该使用 size_t 或 ssize_t

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

在我的代码中,我不使用 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/

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