Working with C++0x/C++11: nullptr and nullptr_t

One my pet peeves with C/C++ are null pointers – specifically not having a good way of specifying a special pointer value that means “invalid pointer”. C (and C++) have a preprocessor macro NULL, which in C expands to either (void*)0 or 0. C++ is different has NULL defined to 0. Zero is a fine representation of an invalid pointer value, but it has nothing inherently invalid it, it can still be used as an address. What nullptr as a keyword brings to the table is the ability to unambiguously inform the compiler and the running code that this pointer isn’t valid.

But another interesting thing is that nullptr is a keyword, and not a type. It’s a what, a keyword? If this doesn’t seem like a great thing, look at it this way; If you have a bool, and want to check its value it will be either true of false. true and false are keywords. And now we have a keyword for “invalid pointer”. Get it now? If a pointer value is nullptr it’s null and pointing at something invalid. It’s also strongly typed so that will aid in disambiguating from non-null pointers in addition to other types. What’s nullptr’s type? It’s of type nullptr_t. Looking back to our bool example, the keywords “true” and “false” are of type bool, and the keyword “nullptr” is of type nullptr_t. This also allows you to use it (for example) in a function definition to catch those instances when a nullptr instead of something else a pointer could be converted to is passed in.

So if you have various function prototypes…

void Foo(long a) { cout << "Foo(long)" << endl; }
void Foo(int a) { cout << "Foo(int)" << endl; }
void Foo(char *a) { cout << "Foo(char*)" << endl; }
void Foo(void* a) { cout << "Foo(void*)" << endl; }
void Foo(nullptr_t a) { cout << "Foo(nullptr_t)" << endl; }

Foo((void*)0); // Foo(void*)
Foo(0); // Foo(int)
Foo(5.5f); // Foo(float) if it’s defined else Foo(int)
//    but usually you’ll get a conversion warning
Foo(NULL); // Foo(int) or Foo(long) on some machines – depends on how NULL is defined
Foo(nullptr); // Foo(nullptr_t) if it’s defined, else Foo(char*)

In some instances you’ll get a compiler warning about an ambiguous overloaded call. nullptr isn’t yet in all C++ compilers, but it will be soon. nullptr’s are a great addition to C++ that made pointer handling much easier.

This entry was posted in C++0X/C++11, Code. Bookmark the permalink.