C++,最佳实践,int 还是 size_t? [英] C++, best practices, int or size_t?

查看:76
本文介绍了C++,最佳实践,int 还是 size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
何时使用 std::size_t?

你好.

假设使用模式相同(即没有负数),最好用于各种索引,intsize_t 类型?

Assuming usage patterns are the same (i.e. no negative numbers), which is preferable to use for various indexes, int or size_t type?

您在 64 位 Intel 上的体验是否存在性能差异?

Is there performance difference in your experience on 64-bit Intel between the two?

谢谢

推荐答案

size_t 是在使用相对泛型数组时应该用于数组索引的类型.IE.当您只有一组抽象的 chars、ints 或其他东西时.

size_t is the type that should be used for array indexing when you work with a relatively generic arrays. I.e. when you have just an array of abstract chars, ints or something else.

当您使用特定数组时,即包含一些特定于您的应用程序的元素的数组,您通常应该已经有一个选择类型"来计数或索引实体在您的应用程序中键入.这就是你应该使用的类型.例如,如果某个数组包含公司员工的记录,那么您的程序中应该已经有一个选择类型",用于指定员工数量".这是您应该用于索引员工记录数组的类型.它可以是 unsigned int,也可以是 employee_count_t 或类似的东西.为此目的使用裸 size_t 是设计错误.

When you are working with a specific array, i.e. an array that contains some elements specific for your application, you should normally already have a "type of choice" to count or to index the entities of that type in your application. That's the type you should use. For example, if some array contains the records for company employees, then you should already have a "type of choice" in your program that you use to designate the "quantity of employees". That's the type you should use for indexing arrays of employee records. It could be unsigned int, it could be employee_count_t or something like that. Using a naked size_t for that purpose is a design error.

另请注意,size_t 不是立即用于数组索引的类型.它是一种旨在表示程序中最大对象大小的类型.它通过传递性对数组起作用":数组是对象,因此 size_t 总是足以索引数组.然而,当你设计一个程序时,考虑通用的容器比考虑特定的数组更有意义.今天它可能是一个数组,明天你可能不得不切换到一个链表或一棵树.在一般情况下,size_t 的范围不足以表示抽象容器中元素的数量,这就是为什么在这种情况下 size_t 不是一个好的选择.

Note also, that size_t is a type not immediately intended for array indexing. It is a type intended to represent the size of the largest object in the program. It "works" for arrays by transitivity: arrays are objects, hence size_t is always enough to index an array. However, when you design a program it makes more sense to think in terms of generic containers, instead of thinking in terms of specific arrays. Today it might be an array, tomorrow you might have to switch to a linked list or a tree instead. In general case, the range of size_t is not sufficient to represent the number of elements in an abstract container, which is why size_t in such cases is not a good choice.

这篇关于C++,最佳实践,int 还是 size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆