nullptr

In C++03, there is no concept of null built in to the language. For anyone familiar with C# or Java, this is quite surprising.

Prior to C++11, the NULL literal was typically used to overcome this omission.

However, there are some downsides to using NULL:

  • The NULL literal is implementation-defined so it could, for example, be an integral type or a pointer type.
  • The appropriate header file may need to be included.
  • You can get caught out when building on different compilers e.g. in a cross platform environment.

C++11 introduces the nullptr keyword to overcome these issues. In most scenarios, nullptr can be used as a drop-in replacement for NULL.

Of course, there are some subtleties. The following function-overloading example demonstrates how a C++11 compiler treats nullptr as a pointer type rather than a numeric type:

void output(int value)
{
  printf("%i\n", value);
}

void output(void* ptr)
{
  printf("%p\n", ptr);
}

output(0);       // Displays integer
output(nullptr); // Displays pointer
output(NULL);    // Displays integer

Although this is a relatively minor addition to the standard, it is a great feature to adopt when writing new code. It makes the programmer’s intentions more clear and it may just help the compiler to pick up errors before the code is deployed.