When to Use nullptr
In C code, pointers can be initialized to conceptually equivalent values: nullptr, NULL, or 0. While these values all indicate a null pointer, nullptr offers several advantages.
Overloaded Function Invocation
Consider the following overloaded functions:
void f(char const *ptr); void f(int v);
In the absence of nullptr, the following call would lead to ambiguity:
f(NULL); //which function will be called?
However, using nullptr clarifies the intended function invocation:
f(nullptr); //first function is called
Template Specialization for nullptr
Additionally, nullptr allows for template specialization specifically for null pointers. Consider the following template:
template<typename T, T *ptr> struct something{}; //primary template
The following partial specialization can be defined for nullptr:
template<> struct something<nullptr_t, nullptr>>{}; //partial specialization for nullptr
This enables creating a dedicated overload for handling nullptr arguments:
template<typename T> void f(T *ptr); //function to handle non-nullptr argument void f(nullptr_t); //an overload to handle nullptr argument!!!
Type Deduction for nullptr
In templates, the type of nullptr is deduced as nullptr_t. This simplifies the code, as seen below:
template<typename T> void f(T *ptr); //function to handle non-nullptr argument void f(nullptr_t); //an overload to handle nullptr argument!!!
The above is the detailed content of When Should You Use `nullptr` in C ?. For more information, please follow other related articles on the PHP Chinese website!