C++ 应该使用 size_t 或 ssize_t
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15739490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
should use size_t or ssize_t
提问by hgyxbll
At my code, I do not use int or unsigned int. I only use size_t or ssize_t for portable. For example:
在我的代码中,我不使用 int 或 unsigned int。我只使用 size_t 或 ssize_t 进行便携。例如:
typedef size_t intc; // (instead of unsigned int)
typedef ssize_t uintc; // (instead of int)
Because strlen
, string
, vector
... all use size_t
, so I usually use size_t
. And I only use ssize_t
when it may be negative.
因为strlen
,string
,vector
...全部使用size_t
,所以我通常使用size_t
。我只ssize_t
在它可能是负面的时候使用。
But I find that:
但我发现:
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.
无符号整数类型非常适合将存储视为位数组的用途。使用 unsigned 而不是 int 来获得更多位来表示正整数几乎从来都不是一个好主意。试图通过声明变量无符号来确保某些值是正的通常会被隐式转换规则打败。
in the book The C++ Programming Language.
在《C++ 编程语言》一书中。
So I am puzzled. Am I wrong? Why does the STL not abide by the suggest on the book?
所以我很困惑。我错了吗?为什么STL不遵守书上的建议?
回答by maditya
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
ssize_t
用于其返回值可以是有效大小或表示错误的负值的函数。保证能够至少在范围内存储值[-1, SSIZE_MAX]
(SSIZE_MAX
取决于系统)。
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
因此,size_t
无论何时打算以字节为单位返回大小,以及ssize_t
何时返回以字节为单位的大小或(负)错误值,都应使用。
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
请参阅:http: //pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
回答by user657267
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
ssize_t
不包含在标准中并且不可移植。size_t
在处理对象的大小时应该使用它(也有ptrdiff_t
指针差异)。