When to use std::size_t?(何时使用 std::size_t?)
问题描述
我只是想知道我应该使用 std::size_t 代替 int 来代替循环和其他东西吗?例如:
I'm just wondering should I use std::size_t for loops and stuff instead of int?
For instance:
#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 的最佳实践是什么?
In general, what is the best practice regarding when to use std::size_t?
推荐答案
一个好的经验法则是,对于任何你需要在循环条件中与自然是 std::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 是任何 sizeof 表达式的类型,并且保证能够在 C++ 中表达任何对象(包括任何数组)的最大大小.通过扩展,它还保证对于任何数组索引都足够大,因此它是数组上按索引循环的自然类型.
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.
如果您只是计算一个数字,那么使用保存该数字的变量类型或 int 或 unsigned int 可能更自然(如果足够大)因为这些应该是机器的自然尺寸.
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.
这篇关于何时使用 std::size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时使用 std::size_t?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
