NULL
has been overtaken from C into C++ and - prior to C++11 - adopted its C meaning:
until C++11: The macro NULL is an implementation-defined null pointer
constant, which may be an integral constant expression rvalue of
integer type that evaluates to zero.
C++11 then introduced a dedicated null pointer literal nullptr
of type std::nullptr_t
. But - probably for backward compatibility - the macro NULL
was not removed; its definition was just a bit relaxed in that compilers may now define it either as integral or as pointer type:
C++11 onwards: an integer literal with value zero, or a prvalue of
type std::nullptr_t
If you use NULL
, then you get implementation-defined behaviour in overload resolution. Consider, for example, the following code with a compiler that uses the integral-version of NULL
-macro. Then a call using NULL
as parameter passed to a function may lead to ambiguities:
struct SomeOverload {
SomeOverload(int x) {
cout << "taking int param: " << x << endl;
}
SomeOverload(void* x) {
cout << "taking void* param: " << x << endl;
}
};
int main() {
int someVal = 10;
SomeOverload a(0);
SomeOverload b(&someVal);
// SomeOverload c(NULL); // Call to constructor is ambiuous
SomeOverload d(nullptr);
}
So it is recommended to use nullptr
where ever you want to express pointer type.
And don't use __null
, as this is a compiler-specific, non-portable constant; nullptr
, in contrast, is perfectly portable.
__null
. If it's an implementation detail, it's not portable to use it. If it's defined by the project, it's using a name reserved for use by the implementation, it's not legal to use that identifier and it should be removed from the project.NULL
usenullptr
. If that doesn't compile then you don't have a pointer and you are doing the wrong thing.nullptr
- always.