Originally posted as TotW #141 on January 19, 2018
by Samuel Freilich (sfreilich@google.com)
Two Kinds of Null Pointer Checks
Checking a pointer for null before dereferencing is important to avoid crashes and bugs. This can be done in two ways:
if (foo) DoSomething(foo);
if (foo != nullptr) DoSomething(*foo);
Both of these conditionals have the same semantics given that foo is a pointer, but the type-checking on the latter is a little tighter. Many types in C++ can be implicitly converted to bool, and additional caution is required when the pointed-to type can itself be converted to bool.
Consider the following code which could have two very different meanings:
// Bad code bool is_migrated = ...;
// Is this checking that is_migrated
is not null, or was the actual // intent (...)