是 size_t 总是 unsigned int

Is size_t is always unsigned int

是否有任何实现将 size_t 定义为 unsigned int 以外的其他内容?在我工作的每个系统下,它都被定义为unsigned int,所以我只是好奇。

没有。但它是一个无符号的 integer 类型。它不需要具体是 int

对于 C++

http://en.cppreference.com/w/cpp/types/size_t

C++ 标准第 18.2.6 节

The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.

对于linux; “Where is c++ size_t defined in linux”给出 long unsigned int

对于 C

(问题最初被标记为 C 和 C++。)

看看这里的答案:

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

x86-64和aarch64(arm64)Linux,OSX和iOS都有size_t最终定义为unsigned long。 (这是 LP64 模型。这种东西是平台 ABI 的一部分,它还定义了函数调用约定等东西。其他架构可能会有所不同。)即使是 32 位 x86 和 ARM 架构也使用 unsigned long OSes,尽管在这些情况下 long 恰好与 int 相同。

我相当确定它是 Win64 上的 unsigned __int64/unsigned long long。 (使用 LLP64 模型)

没有。我只是 运行 这个程序在 cpp.sh 上,它是 gcc:

#include <iostream>

int main()
{
  std::cout << sizeof(unsigned int) << " " << sizeof(unsigned long) << " " << sizeof(size_t) << "\n";
}

它产生这个输出:

4 8 8

来自sys/types.h man page :

size_t shall be an unsigned integer type.

所以至少理论上它可以是无符号的 shortintlonglong long.

不是,是无符号整数类型(不是unsigned int)。来自 CPPReference

std::size_t is the unsigned integer type of the result of the sizeof operator

但是你不能确切地说出它的大小,我想这取决于平台。

绝对不能保证 size_t 被定义为任何 "concrete" 类型。实际上,如果您想查看不是 unsigned int 的系统,请查看我的机器 (unsigned long),以及大多数 64 位 GNU/Linux 系统。

来自 N4296,第 18.2.6 节:

The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size bytes of any object.

此外,来自 N897(基本原理)6.5.3.4...

The type of sizeof, whatever it is, is published (in the library header <stddef.h>) as size_t, since it is useful for the programmer to be able to refer to this type. This requirement implicitly restricts size_t to be a synonym for an existing unsigned integer type. Note also that, although size_t is an unsigned type, sizeof does not involve any arithmetic operations or conversions that would result in modulus behavior if the size is too large to represent as a size_t, thus quashing any notion that the largest declarable object might be too big to span even with an unsigned long in C89 or uintmax_t in C9X. This also restricts the maximum number of elements that may be declared in an array, since for any array a of N elements,

N == sizeof(a)/sizeof(a[0])

Thus size_t is also a convenient type for array sizes, and is so used in several library functions.

没有。 size_t 可以而且确实不同于 unsigned int

根据 C standard, 6.5.3.4:

The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

在C标准下,size_t是一个未定义的无符号整数类型。

根据 Open Group (POSIX, etc):

64-bit and Data Size Neutrality

...

sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) = sizeof(size_t)

简单地说:

size_tsize_t。不符合那个的代码是错误的。