为什么 std::size_t 在 32 位系统上是 4 个字节,而 unsigned long long 在 32 位和 64 位系统上都是 8 个字节?

Why is std::size_t 4 bytes on 32bit systems when unsigned long long is 8 bytes on both 32bit and 64 bit systems?

问题很简单

在 32 位系统上:

std::cout << sizeof(unsigned int);        //4
std::cout << sizeof(unsigned long long);  //8
std::cout << sizeof(std::size_t);         //4

在 64 位系统上:

std::cout << sizeof(unsigned int);        //4
std::cout << sizeof(unsigned long long);  //8
std::cout << sizeof(std::size_t);         //8

我只看了MSVC的实现,大概是这样的:

#ifdef _WIN64
    typedef unsigned __int64 size_t;
#else
    typedef unsigned int     size_t;
#endif

那么为什么不在 32 位和 64 位系统上都明确支持 std::size_t unsigned long long (std::uintmax_t) 呢?还是我错了?

size_t的重点是能够容纳尽可能大的物体的大小。在 32 位系统上,任何对象都不能占用超过 2**32 字节,因此 32 位类型就足够了。

使用 64 位类型会浪费 space 并且可能会花费 运行 时间。

那将是毫无意义的浪费。在 32 位机器上,您有一个 4 GB 地址 space,因此您不能拥有大于 4 GB 的对象,因此 32 位 size_t 的范围完全足够。