Friday, October 26, 2012

The Standard works in Circular Ways

Rummaging around in the C++11 standard isn't all fun and games, but from time to time you come across true gems.  For example, this is from 2.14.7/1 in the standard:
The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t.
And this is from 18.2/9:
nullptr_t is defined as follows:
namespace std {
  typedef decltype(nullptr) nullptr_t;
So nullptr is of type nullptr_t, and nullptr_t is defined to be the type of nullptr.

Um, okay.



Tianyu Zhu said...

Probably so that it doesn't get cast to int, right?

Tianyu Zhu said...
This comment has been removed by the author.
Scott Meyers said...

@Tianyu Zhu: I don't know why they defined things the way they did, but there are other ways to define things such that casting to int is not permitted (without a reinterpret_cast).

Anonymous said...

That's a somewhat consecrated design, also present in Scala and D. "nullptr" is a bottom type in the type lattice just above the "none" type that cannot be instantiated. As such, it has its own interesting properties - most notably it can be instantiated but only with null.

Defining nullptr_t as "the type of nullptr" is a simple solution to avoiding introducing a new keyword for that type.

Anonymous said...

For me really surprising thing about nullptr is that it is not a pointer, i.e. std::is_pointer<decltype(nullptr)>::value == false. For me it's yet another defect in the C++11.