nullptr
doean’t suffer from the overloading problem or the template deduction problem that 0 and NULL
are susceptible to. It also improves code clarity.
In C++98, a null pointer can be represented by an int
0 or NULL
1, which introduses some controdiction between the apparent meaning (mean to refer to a null pointer) and actual meaning (the representation is some kind of integer). Neither 0
nor NULL
has a pointer type - it’s just that C++ will (reluctently) interpret them as a null pointer in the context where a pointer a pointer is wanted but can’t be found.
That’s why nullptr
is introduced: its type is not integral, but std::nullptr_t
2, which could be treated as a pointer of all types due to its ability to implicitly convert to all raw pointer types.
Compared with 0 and NULL
, the obvious advantages shown by nullptr
is its better support for overloading and template, as well as its improved code clarity.
Overloading
|
|
Template
Inside a template, if an int
or NULL
(which is int
-like type) is being passed to a function that requires a pointer, type errors occur:
|
|
In contrast, here, when nullptr
is passed to lockAndCall
, the type for ptr
is deduced to be std::nullptr_t
instead of previous int
(or int
-like one), and when ptr
is passed to f3
, there is an implicit conversion from std::nullptr_t
to Widget*
.
Code clarity
Using 0, the return type may not be obvious, is it an integral type or a pointer type?
|
|
There’s no ambiguity when using nullptr
:
|
|