我应该使用无符号整数来计数会员吗? [英] Should I use unsigned integers for counting members?

查看:109
本文介绍了我应该使用无符号整数来计数会员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



答案



例如,假设一个类

  TList< T> = class 
private
FCount:Cardinal;
public
属性Count:Cardinal read FCount;
结束

这是有道理的,不是吗?存储在列表中的项目数量不能为负数,那么为什么不使用无符号整数类型呢?我认为总是使用最小的一般(最特殊的)类型是一个很好的原则。



现在,迭代列表看起来像这样:对于I:= 0到List.Count - 1 do
Writeln(List [I]); p>

  

当列表中存储的项目数为零时,编译器尝试评估

  List.Count  -  1 

这会导致一个很好的整数溢出(下溢到准确的)。结合调试器没有显示发生异常的适当位置的事实,这对我来说很难找到。



让我补充一点,如果你有溢出检查已关闭,所导致的错误将更难跟踪,因为那时您将经常访问不属于您的记忆体,并导致未定义的行为。



从现在开始,我将会为所有的会员使用纯整数,以避免这种情况。



如果这是完整的废话,请指出给我:)



(我刚刚花了一个小时跟踪整数溢出在我的代码,所以我决定分享 - 大多数人在这里会知道当然,但也许我可以保存某人有时间。)

解决方案

不,绝对不是。 Delphi成语是在这里使用整数。不要打语言。
在32位环境中,除了您尝试构建位图之外,您不会有更多元素。



让我们清楚一点:每个程序员谁将要使用你的代码会讨厌你使用红衣主教而不是一个整数。


Should I use unsigned integers for my count class members?

Answer

For example, assume a class

TList <T> = class
private
  FCount : Cardinal;
public
  property Count : Cardinal read FCount;
end;

That does make sense, doesn't it? The number of items stored in a list can't be negative, so why not use an unsigned integer type for it? I think it's in general a good principle to always use the least general (ergo the most special) type possible.

Now, iterating over a list looks like this:

for I := 0 to List.Count - 1 do
  Writeln (List [I]);

When the number of items stored in the list is zero, the compiler tries to evaluate

List.Count - 1

which results in a nice Integer overflow (underflow to be exact). Combined with the fact that the debugger does not show the appropriate location where the exception occured, this was very hard to find for me.

Let me add that if you have overflow checking turned off, the resulting errors will be even harder to track, because then you will often access memory that doesn't belong to you - and that results in undefined behaviour.

I will be using plain Integers for all my count members from now on to avoid situations like this.

If that's complete nonsense, please point it out to me :)

(I just spent an hour tracking an integer overflow in my code, so I decided to share that - most people on here will know that of course, but perhaps I can save someone some time.)

解决方案

No, definitely not. Delphi idiom is to use integers here. Don't fight the language. In a 32 bit environment you'll not have more elements in the list, except if you try to build a bitmap.

Let's be clear: every programmer who is going to have to use your code is going to hate you for using a Cardinal instead of an integer.

这篇关于我应该使用无符号整数来计数会员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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