Why are unsigned integers error prone?

后端 未结 8 1096
眼角桃花
眼角桃花 2020-12-13 08:28

I was looking at this video. Bjarne Stroustrup says that unsigned ints are error prone and lead to bugs. So, you should only use them when you really need t

8条回答
  •  星月不相逢
    2020-12-13 08:41

    Although it may only be considered as a variant of the existing answers: Referring to "Signed and unsigned types in interfaces," C++ Report, September 1995 by Scott Meyers, it's particularly important to avoid unsigned types in interfaces.

    The problem is that it becomes impossible to detect certain errors that clients of the interface could make (and if they could make them, they will make them).

    The example given there is:

    template 
      class Array {
      public:
          Array(unsigned int size);
      ...
    

    and a possible instantiation of this class

    int f(); // f and g are functions that return
    int g(); // ints; what they do is unimportant
    Array a(f()-g()); // array size is f()-g()
    

    The difference of the values returned by f() and g() might be negative, for an awful number of reasons. The constructor of the Array class will receive this difference as a value that is implicitly converted to be unsigned. Thus, as the implementor of the Array class, one can not distinguish between an erreonously passed value of -1, and a very large array allocation.

提交回复
热议问题