C++ – Advantages of Using nullptr

c++c++-faqc++11nullnullptr

This piece of code conceptually does the same thing for the three pointers (safe pointer initialization):

int* p1 = nullptr;
int* p2 = NULL;
int* p3 = 0;

And so, what are the advantages of assigning pointers nullptr over assigning them the values NULL or 0?

Best Answer

In that code, there doesn't seem to be an advantage. But consider the following overloaded functions:

void f(char const *ptr);
void f(int v);

f(NULL);  //which function will be called?

Which function will be called? Of course, the intention here is to call f(char const *), but in reality f(int) will be called! That is a big problem1, isn't it?

So, the solution to such problems is to use nullptr:

f(nullptr); //first function is called

Of course, that is not the only advantage of nullptr. Here is another:

template<typename T, T *ptr>
struct something{};                     //primary template

template<>
struct something<nullptr_t, nullptr>{};  //partial specialization for nullptr

Since in template, the type of nullptr is deduced as nullptr_t, so you can write this:

template<typename T>
void f(T *ptr);   //function to handle non-nullptr argument

void f(nullptr_t); //an overload to handle nullptr argument!!!

1. In C++, NULL is defined as #define NULL 0, so it is basically int, that is why f(int) is called.

Related Question