NULL is the billion-dollar mistake but there is nothing in the type system of C++ to prevent it. However, C++ already has const-correctness so implementing
NULL-correctness seems trivial:
- introduce a keyword,
__nonnull, as a specifier in the same class as
const, which can only be placed after the
*in a declaration.
- All pointers obtained by
__nonnullpointer value or
constreference can be automatically converted to a normal pointer, but not vice-versa without a cast. (
T *__nonnullcan be converted to
T *, and
T *__nonnull &can be converted to
T *const &)
Writable references of pointers cannot be automatically converted between normal and
T *__nonnull &CANNOT be converted to
T *&), i.e.
int x; int *__nonnull p = &x; int *q = p; // OK int *const &r = p; // OK int *const *s = &p; // OK int *&t = p; // ERROR, don't want to assign NULL to t int **u = &p; // ERROR, don't want to assign NULL to *u
const_castcan be used to cast a normal pointer to a
__nonnullpointer, in which if the pointer is really
NULL, the behaviour is undefined.
- Assigning a null-pointer constant
__nonnullpointer variable is an error.
__nonnullpointers cannot be default initialised, like a reference.
- Have a standard library function to convert a normal pointer to a
__nonnullpointer, which throws an exception on
- An optional warning will be given by compiler for dereferencing normal pointers without
NULLcheck, which the practice is going to be deprecated.
Is the above proposal viable? Are the above things enough for a
NULL-safe type system?