Whats better to use in C++11 , Zero or NULL?
Neither, it's nullptr
.
Though, in your case, I'd just go with
if ( !p ){
//something
}
2.14.7 Pointer literals [lex.nullptr]
1 The pointer literal is the keyword
nullptr
. It is a prvalue of typestd::nullptr_t
. [ Note:std::nullptr_t
is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.
The other answers are right. But I wanted to say a little more about why nullptr
is better.
In C++11 "perfect forwarding" is very important. It is used everywhere. Obvious places are bind
and function
. But it is also used in a multitude of other places under the covers. But "perfect forwarding" isn't perfect. And one of the places it fails is null pointer constants.
template <class T>
void display(T)
{
std::cout << type_name<T>() << '\n';
}
template <class T>
void
f(T&& t)
{
display(std::forward<T>(t)); // "perfectly forward" T
}
int main()
{
f(0);
f(NULL);
f(nullptr);
}
With an appropriate definition of type_name<T>()
, on my system this prints out:
int
long
std::nullptr_t
This can easily make the difference between working code and errors. With any luck your errors will come at compile time (with horrible error messages). But you may also get run time errors in some circumstances.
Aggressively ban use of 0 and NULL in your code.
Even if you're not perfect forwarding in your code, code you call (such as the std::lib) is very likely using it under the covers.
C++11 has a new literal keyword nullptr
. It's better than 0
or NULL
for things like this because there's no chance it will be used as an int
in overload resolution.
if ( nullptr == p )
Or of course you can just use a pointer in a bool context:
if ( !p )