Signed Size
Use Int (i.e. signed) as the return type for *.size().
Mixing signed and unsigned integers is error-prone, and even pure unsigned arithmetic is often unintuitive and dangerous.
Classic C/C++ pitfall:
size_t i = 9;
while (i >= 0) {
--i;
}
This is an endless loop, as i is always >= 0.
With unsigned 0 - 1 is not -1 but 0xffffffffffffffff, i.e. a really big, positive integer.
When working with sizes, subtraction is common. The moment you compute differences, you need a signed type anyway. So just use Int, then , Size, and SSize are unnecessary.
PtrDiffUInt should be reserved for cases like hardware registers, bit masks, flags, and hashes — not used for sizes.
Anyone who needs more than 2GB of data in a single “byte array”, should please use a 64 bit platform.
For bounds checking, the two comparisons x >= 0 and x < width may very well be reduced to a single UInt(x) < width by the compiler in an optimization step.
The C++ Experts About It
See also Going Native 2012, Day 2, Interactive Panel: Ask Us Anything
- 12:53 - 13:10
Bjarne Stroustrup:
“Use ints until you have a reason not to.
Don’t use unsigned unless you are fiddling with bit patters.
Never mix signed and unsigned.” - 42:41 - 45:28
Bjarne Stroustrup and Herb Sutter recommend using signed integer. - 1:02:51 - 1:03:14
Herb Sutter and Chandler Carruth about unsignedsize_tin the C++ STL containers: “They are wrong”, “We are sorry”