本文介绍了在C ++中使用size_t是个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到人们使用 size_t ,当它们意味着一个无符号整数。例如:

  class Company {
size_t num_employees_;
// ...
};

这是好的做法吗?一件事是你必须包括< cstddef> 。应该是 unsigned int 吗?或者甚至只是 int



使用 int 听起来很吸引我,因为它避免了像这样的愚蠢的错误(因为人们经常使用 int ):

  for(int i = num_employees_  -  1; i& = 0; --i){
//使用employee_ [i]
执行某项操作


可能与 int 的大小不同。 / p>

对于像员工人数等等,这种差异通常是无关紧要的;一个人有多于2 ^ 32名员工?但是,如果您使用 size_t 代替 int 文件系统支持64位文件。



请注意,对象大小(由 sizeof 获得) code> size_t ,而不是 int unsigned int ;相应地,对于两个指针之间的差异(例如,& a [5] - & a [0] =< = ptrdiff_t(5))。


I've seen people use size_t whenever they mean an unsigned integer. For example:

class Company {
  size_t num_employees_;
  // ...
};

Is that good practice? One thing is you have to include <cstddef>. Should it be unsigned int instead? Or even just int?

Just using int sounds attractive to me since it avoids stupid bugs like these (because people do often use int):

for(int i = num_employees_ - 1; i >= 0; --i) {
   // do something with employee_[i]
}
解决方案

size_t may have different size to int.

For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use size_t instead of int, if your filesystem supports 64-bit files.

Do realise that object sizes (as obtained by sizeof) are of type size_t, not int or unsigned int; also, correspondingly, there is a ptrdiff_t for the difference between two pointers (e.g., &a[5] - &a[0] == ptrdiff_t(5)).

这篇关于在C ++中使用size_t是个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:25