我只是想知道我是否应该使用std::size_t for循环之类的东西,而不是int? 例如:
#include <cstdint>
int main()
{
for (std::size_t i = 0; i < 10; ++i) {
// std::size_t OK here? Or should I use, say, unsigned int instead?
}
}
一般来说,关于何时使用std::size_t的最佳实践是什么?
我只是想知道我是否应该使用std::size_t for循环之类的东西,而不是int? 例如:
#include <cstdint>
int main()
{
for (std::size_t i = 0; i < 10; ++i) {
// std::size_t OK here? Or should I use, say, unsigned int instead?
}
}
一般来说,关于何时使用std::size_t的最佳实践是什么?
当前回答
Size_t是一种非常易读的方式来指定项的大小维度——字符串的长度,指针占用的字节数,等等。 它也可以跨平台移植——你会发现64位和32位都可以很好地使用系统函数和size_t——这是unsigned int可能做不到的(例如,什么时候应该使用unsigned long
其他回答
我一直在努力理解什么时候使用它。但size_t只是一个无符号整型数据类型,它定义在各种头文件中,如<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>等。
It is used to represent the size of objects in bytes hence it's used as the return type by the sizeof operator. The maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef (alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative(excluding ssize_t) Therefore many C library functions like malloc, memcpy and strlen declare their arguments and return type as size_t.
/ Declaration of various standard library functions.
// Here argument of 'n' refers to maximum blocks that can be
// allocated which is guaranteed to be non-negative.
void *malloc(size_t n);
// While copying 'n' bytes from 's2' to 's1'
// n must be non-negative integer.
void *memcpy(void *s1, void const *s2, size_t n);
// the size of any string or `std::vector<char> st;` will always be at least 0.
size_t strlen(char const *s);
Size_t或任何无符号类型可能被视为循环变量,因为循环变量通常大于或等于0。
一个很好的经验法则是,对于需要在循环条件中与std::size_t本身的东西进行比较的任何东西。
std::size_t是任何sizeof表达式的类型,as被保证能够在c++中表示任何对象(包括任何数组)的最大大小。通过扩展,它也保证足够大,可以用于任何数组下标,因此它是数组上按下标循环的自然类型。
如果你只是数到一个数字,那么使用保存该数字的变量类型或int或unsigned int(如果足够大)可能更自然,因为这些应该是机器的自然大小。
Size_t是sizeof操作符的结果类型。
size_t用于对数组的大小或索引进行建模的变量。Size_t传达语义:您立即知道它表示字节或索引的大小,而不仅仅是另一个整数。
此外,使用size_t表示字节大小有助于使代码可移植。
size_t是一种无符号类型,它可以为您的体系结构保存最大整数值,因此它不会因为符号(有符号int 0x7FFFFFFF加1会得到-1)或短大小(无符号短int 0xFFFF加1会得到0)而导致整数溢出。
它主要用于数组索引/循环/地址算法等。像memset()这样的函数只接受size_t,因为理论上你可能有一个大小为2^32-1的内存块(在32位平台上)。
对于这样简单的循环,不要麻烦,只使用int。
根据定义,size_t是sizeof操作符的结果。创建Size_t是为了引用大小。
你做某事的次数(在你的例子中是10次)与大小无关,那么为什么要使用size_t呢?Int,或者unsigned Int,应该是可以的。
当然,你在循环中对i做什么也是相关的。例如,如果将它传递给一个接受无符号整型的函数,则选择无符号整型。
在任何情况下,我都建议避免隐式类型转换。使所有类型转换显式。