nullptr in C++11
17 Jan 2013It happened! It finally happened! NULL
has a real identity within the language. Forever I’d used the notion of NULL
in my C & C++ to really mean 0
(zero) under the covers.
#define NULL 0
Of course, I’d never defined it myself. It was always done for me in one of the many include files drawn into my program. One of the problems with this particular define is for overloaded methods. If you were to pass NULL
in its defined state above, you’d be guessing as to which overload is called.
void useptr(float* p) { /*...*/ }
void useptr(char* p) { /*...*/ }
// float* or char*??
useptr(NULL);
Well, now we have nullptr
in C++11. nullptr
is castable to any pointer type.
int* p = nullptr;
char* str = nullptr;
person* someone = nullptr;
The castability also covers off on boolean expressions, so the following if-trees will still work.
if (!p) {
cout << "p was null!";
}
Finally, nullptr
is of type nullptr_t
. If you’re going to find it of use to you to guarantee that a null pointer is going to be passed into a method, you could type your method using the type nullptr_t
.
Null now has a home.