Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are objects of type nullptr_t ever needed?

Tags:

c++

c++11

nullptr

Quoting C++11: (18.2/9)

nullptr_t is defined as follows:

namespace std { typedef decltype(nullptr) nullptr_t; }

The type for which nullptr_t is a synonym has the characteristics described in 3.9.1 and 4.10. [ Note: Although nullptr’s address cannot be taken, the address of another nullptr_t object that is an lvalue can be taken. —end note ]

Do we ever need objects of type nullptr_t (other than nullptr)?

like image 835
embedc Avatar asked Aug 21 '19 13:08

embedc


2 Answers

nullptr is a prvalue, so you cannot take its address. (It is not an object.) The note is referring to cases like this:

nullptr_t n;

Then, n is an ordinary object of type nullptr_t so you can take its address. This doesn’t seem to be useful whatsoever, but in generic code this feature may come in somehow.

like image 112
L. F. Avatar answered Oct 27 '22 12:10

L. F.


It's useful in this instance, which is good enough for me:

#include <cstddef>
#include <iostream>
#include <limits>

int bonus(int){return std::numeric_limits<int>::max();}
int bonus(std::nullptr_t){return 0;}

int main()
{
    std::nullptr_t bar;
    std::cout << bonus(0) << "\n";
    std::cout << bonus(nullptr) << "\n";
    std::cout << bonus(bar) << "\n";
}

C++ is a general purpose language and it would be annoying if the type associated with nullptr was not part of the overload resolution system.

like image 38
Bathsheba Avatar answered Oct 27 '22 12:10

Bathsheba