More C++ Idioms/nullptr

= nullptr =

Intent
To distinguish between an integer 0 and a null pointer.

Motivation
For many years C++ had an embarrassment of not having a keyword to designate a null pointer. C++11 has eliminated that embarrassment. C++'s strong type checking makes C's NULL macro almost useless in expressions, e.g.:

Instead,

or

are valid definitions for NULL in C++. See below.

The crux of the matter, in fact, is that C++ disallows conversions from void *, even when the value is a constant zero, but, for constant zero, introduces a special case anyway: int to pointer (actually several of them: short to pointer, long to pointer, etc.). This is, in fact, even worse than allowing (for the constant case) the former exception, the more so given the support of function overloading in the language.

The use of the macro NULL has its own set of problems as well. C++ requires that macro NULL be defined as an integral constant expression having the value of 0. So unlike in C, NULL cannot be defined as (void *)0 in the C++ standard library. Furthermore, the exact form of definition is left to the particular implementation, which means that e.g. both 0 and 0L are viable options, among some others. This is a trouble as it can cause confusion in overload resolution. Worse, the way confusing overload resolution manifests itself will vary depending on the compiler and its settings used. An illustrative case is shown in this slight modification of the example above:

Solution and Sample Code
The nullptr idiom solves some of the above problems and can be put in reusable form, as a library solution. It is a very close approximation of a "null keyword", by using only pre-C++11 standard features.

The following is such a library solution as mostly found in Effective C++ by Scott Meyers, Second Edition, Item 25 (it is not present in the third edition of the book).

The following code illustrates some usage cases (and assumes the class template above has already been #included). Unfortunately, there seems to be a bug in gcc 4.1.1 compiler that does not recognize the comparison of nullptr with point to member function (pmf). The above code compiles on VC++ 8.0 and Comeau 4.3.10.1 beta.

Note that nullptr idioms makes use of the ../Return Type Resolver/ idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to. For example, if nullptr is being assigned to a character pointer, a char type instantiation of the templatized conversion function is created.

Consequences
There are some disadvantages of this technique and are discussed in the N2431 proposal draft. In summary, the disadvantages are
 * A header must be included to use nullptr. In C++11, nullptr itself is a keyword and requires no headers (although std::nullptr_t does).
 * Compilers have historically produced (arguably) unsatisfactory diagnostics when using the code proposed.

Related Idioms

 * ../Return Type Resolver/