Null Pointer
Source: Dev.to
Why use nullptr over NULL or 0
nullptr has the distinct type std::nullptr_t.
Because it is not an integer, overload resolution can differentiate between a null‑pointer argument and an integral argument. This eliminates ambiguous calls that can arise with NULL (typically defined as 0) or a literal 0.
Function overloading example
void func(int);
void func(bool);
void func(void*);Calls with different null representations
func(0); // Calls func(int)
func(NULL); // Also calls func(int) because NULL is usually defined as 0Both 0 and NULL are integral constants, so the overload taking an int is a better match than the one taking a void*.
Using nullptr to select the pointer overload
func(nullptr); // Calls func(void*)Because nullptr is of type std::nullptr_t, it converts only to pointer types, allowing the pointer overload to be chosen unambiguously.
Readability with auto and nullptr
auto result = findRecord(...);
if (result == 0) {
// …
}
if (result == nullptr) {
// …
}The second comparison makes it clear that result is a pointer, improving code readability.
Fun Fact
When you allocate a non‑temporary object on the heap:
int* p = new int;the pointer returned by new is an r‑value, but it points to an l‑value (the newly created object). Dereferencing a pointer yields an l‑value reference, and the object itself is an l‑value because it has a stable address.