Using nullptr: Advantages over NULL and 0
Pointers must be properly initialized to avoid unexpected behavior. While the syntax int* p1 = nullptr;, int* p2 = NULL;, and int* p3 = 0; may seem functionally equivalent, there are significant advantages to using nullptr over the other two options.
Overloading Ambiguity Resolution:
Consider the overloaded functions:
void f(char const *ptr); void f(int v); f(NULL); // ambiguous function call
With NULL, the compiler cannot determine which function to call, as it could be either f(char const *) or f(int). This ambiguity can lead to unexpected errors. However, using nullptr resolves this ambiguity:
f(nullptr); // calls f(char const *)
Template Specialization:
In C , the type of nullptr is nullptr_t. This allows for template specialization for nullptr, providing unparalleled flexibility:
template<typename T, T *ptr> struct something{}; // primary template template<> struct something<nullptr_t, nullptr>{}; // partial specialization for nullptr
Using this specialization, you can handle nullptr arguments uniquely:
template<typename T> void f(T *ptr); // function to handle non-nullptr argument void f(nullptr_t); // overload to handle nullptr argument
The above is the detailed content of Why is `nullptr` a Better Choice than `NULL` and `0` for Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!