In the Google C++ Style Guide, on the topic of \"Unsigned Integers\", it is suggested that
Because of historical accident, the C++ standard also uses unsi
Using unsigned types to represent non-negative values...
The Google Coding Guidelines puts emphasis on the first kind of consideration. Other guideline sets, such as the C++ Core Guidelines, put more emphasis on the second point. For example, consider Core Guideline I.12:
I.12: Declare a pointer that must not be null as
not_null
Reason
To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for
nullptr
.Example
int length(const char* p); // it is not clear whether length(nullptr) is valid length(nullptr); // OK? int length(not_null<const char*> p); // better: we can assume that p cannot be nullptr int length(const char* p); // we must assume that p can be nullptr
By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.
Of course, you could argue for a non_negative
wrapper for integers, which avoids both categories of errors, but that would have its own issues...