在代码库里看到了大量的size_t的使用,特别是在for循环里,一直觉得这个名字并不直观,不知道意义在哪儿,看了下它的定义:1
2
3#define __SIZE_TYPE__ long unsigned int
typedef __SIZE_TYPE__ size_t;
可以看到size_t其实就是long unsigned int(64位系统中, 32位为unsigned int). 它是一个与机器相关的unsigned类型,其大小足以保证存储内存中对象的大小。
size_t的引入增强了程序在不同平台上的可移植性。不同平台的size_t会用不同的类型实现,使用size_t而非int或unsigned可以写出扩展行更好的代码。
而在for循环中,当需i要不断进行比较时,由于size_t可以表示C++中任何对象的最大大小,用size_t最为安全
A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t itself.
std::size_t is the type of any sizeof expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension it is also guaranteed to be big enough for any array index so it is a natural type for a loop by index over an array.
If you are just counting up to a number then it may be more natural to use either the type of the variable that holds that number or an int or unsigned int (if large enough) as these should be a natural size for the machine.