What is the difference between nullptr and nullptr_t in C++?

Quora Feeds

Active Member
Brian Bi

nullptr is a literal, analogous to 42 or 'x' or 3.14. Its value is a null pointer constant, which can be converted into a null pointer of any type.

Meanwhile, std::nullptr_t (note the namespace) is a type, like int or char or double. It is defined to be the type of nullptr.

You can initialize any pointer using nullptr:

int* p1 = nullptr;
std::vector<int>* p2 = nullptr;
void* p3 = nullptr;

The result in each case is a null pointer. Obviously you cannot write
int* p1 = std::nullptr_t;
since putting a type on the right-hand side like that is nonsensical, just like, say,
double x = int;

Similarly you must say std::nullptr_t when you mean the type. Sometimes you will in fact want to write out the type explicitly. For example, consider the following:
void f(T* p);
You can call f(nullptr) and nullptr will be implicitly converted to the null pointer value of type T*. However, if instead you had:

template <class U>
void f(U* p);

then you wouldn't be able to call f(nullptr) since nullptr is not actually a pointer type; it doesn't have a type U* for any U. Furthermore, the compiler wouldn't know what kind of pointer to convert it into (since it can be converted into any kind of pointer). If you want to be able to call f(nullptr), then you need to add a second overload:
void f(std::nullptr_t);
Now this overload will be selected if you call f(nullptr), and everything will be fine. Obviously you can't write this declaration:
void f(nullptr);
That would just be nonsensical.

See Questions On Quora

Continue reading...
 
Top