What are the uses of the type `std::nullptr_t`?
If more than one overload accepts a pointer type, an overload for std::nullptr_t
is necessary to accept a nullptr
argument. Without the std::nullptr_t
overload, it would be ambiguous which pointer overload should be selected when passed nullptr
.
Example:
void f(int *intp)
{
// Passed an int pointer
}
void f(char *charp)
{
// Passed a char pointer
}
void f(std::nullptr_t nullp)
{
// Passed a null pointer
}
There are some special cases that comparison with a nullptr_t
type is useful to indicate whether an object is valid.
For example, the operator==
and operator!=
overloads of std::function
could only take nullptr_t
as the parameter to tell if the function object is empty. For more details you could read this question.