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:
Which function will be called? Of course, the intention here is to call
f(char const *)
, but in realityf(int)
will be called! That is a big problem1, isn't it?So, the solution to such problems is to use
nullptr
:Of course, that is not the only advantage of
nullptr
. Here is another:Since in template, the type of
nullptr
is deduced asnullptr_t
, so you can write this:1. In C++,
NULL
is defined as#define NULL 0
, so it is basicallyint
, that is whyf(int)
is called.