Talk: C++: No more nulls! (Fixing the billion dollar mistake)
I recently worked for several years in a large C# code base where null was banned. It was beautiful! In C++ it can be even better.
Null is a traditional way of indicating "no value", but the approach has several problems:
- All pointers can be null, there's nothing explicit about which ones are actually allowed be so
- Interfaces get harder to understand
- You risk ending up with a lot of pointless null checks
- You risk dereferencing a null pointer
Disallowing null eliminates null pointer dereferencing, makes it explicit which variables might not contain a value, removes unnecessary null checks, and makes the code safer and much easier to reason about.
We'll start with going through the common uses of null (as arguments, return values and members). We'll then look at ways to improve our code by:
- For non-optional values, using non-nullable types (value semantics, references, move semantics)
- For optional values, using C++17's std::optional. (We'll go into detail here, also discussing performance)
Tony Hoare, the inventor of null, calls it his "billion-dollar mistake". Let's see if we can fix it.