Should I use unsigned integers for counting members?

前端 未结 6 1957
自闭症患者
自闭症患者 2021-02-04 14:25

Should I use unsigned integers for my count class members?

Answer

For example, assume a class

TList  = class
private
           


        
6条回答
  •  醉梦人生
    2021-02-04 15:04

    Unsigned integers are almost always more trouble than they're worth because you usually end up mixing signed and unsigned integers in expressions at some point. That means that the type will need to be widened (and probably have a performance hit) to get correct semantics (ideally the compiler does this as per language definition), or else you'll need to be very careful in your range checking.

    Take C/C++ for example: size_t is the type of the integer for memory sizes and allocation, and is unsigned, but ptrdiff_t is the type for the offset you get when you subtract one pointer from another, and necessarily is signed. Want to know how many elements you've allocated in an array? Perhaps you subtract the first element address from the last+1 element address and divide by sizeof(element-type)? Well, now you've just mixed signed and unsigned integers.

提交回复
热议问题