Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the uses of the type `std::nullptr_t`?

Tags:

c++

c++11

nullptr

I learned that nullptr, in addition to being convertible to any pointer type (but not to any integral type) also has its own type std::nullptr_t. So it is possible to have a method overload that accepts std::nullptr_t.

Exactly why is such an overload required?

like image 561
Hindol Avatar asked Aug 22 '12 05:08

Hindol


People also ask

What is std :: nullptr_t?

std::nullptr_t is the type of the null pointer literal, nullptr. It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are null pointer constants (see NULL), and may be implicitly converted to any pointer and pointer to member type.

When to use nullptr_ t?

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.

What is the type of nullptr literal in c++?

nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.

Can a reference be a nullptr?

“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.”


2 Answers

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 } 
like image 163
torrey.lyons Avatar answered Sep 23 '22 13:09

torrey.lyons


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.

like image 38
neuront Avatar answered Sep 20 '22 13:09

neuront