4

In Effective Modern C++, "Iterm 8: Prefer nullptr to 0 and NULL.", Page 59, it says:

nullptr's actual type is std::nullptr_t, and, in a wonderfully circular definition, std::nullptr_t is defined to be the type of nullptr.

A wonderfully circular definition?

How that comes?

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
chaosink
  • 1,329
  • 13
  • 27
  • 2
    It's a trick in the compiler itself – JVApen Aug 18 '18 at 20:32
  • Actural? Is that a misquote? – Yakk - Adam Nevraumont Aug 18 '18 at 20:40
  • You can find some explanation [here](https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr) – Jónás Balázs Aug 18 '18 at 20:40
  • And also [here](https://stackoverflow.com/questions/28696522/where-does-nullptr-t-reside). – Ron Aug 18 '18 at 20:43
  • 5
    The quote is misleading. Although the type of `nullptr` is `std::nullptr_t`, the standard does not use it to define `nullptr`. So there is no circular definition. The behavior of `nullptr` and `std::nullptr_t` are defined by various statements scattered in the standard. – Eric Postpischil Aug 18 '18 at 20:44
  • Joke of the day: `auto p = new decltype(nullptr);` . Do not do this in actual code. – Eljay Aug 18 '18 at 20:48
  • 3
    @Eljay: That would make a non-null `std::nullptr_t *`. – Ben Voigt Aug 18 '18 at 20:58
  • @EricPostpischil You have that backwards, I think. The definition of `nullptr` is literally nothing more than "The pointer literal is the keyword `nullptr`. It is a prvalue of type `std::nullptr_t`." and its useful properties are given to all `nullptr_t` values regardless of whether they come from a `nullptr` literal. But the standard does not rely on `nullptr` in the definition of `nullptr_t` aside from mentioning again, redundantly, that it is the type of that, so there is indeed no circular definition. –  Aug 19 '18 at 15:57

1 Answers1

2

In brief, nullptr is a value that can be assigned to a pointer to any type, and it is false in boolean context (unlike most pointers that are results of new/malloc, or referencing a valid object), and despite itself being a valid pointer, dereferencing it results in UB, as does in/decrementing it, and it is a sole value of a singleton type nullptr_t.

Something like this.

bipll
  • 11,747
  • 1
  • 18
  • 32
  • that reads like a random pointer not holding a value returned by malloc/new or something returned by the address-of operator would magically would evaluate to `false` when converted to `bool`. – Swordfish Aug 18 '18 at 21:29
  • 1
    @M.M: as well as `new` (e.g. in `new (std::nothrow)`) – Andriy Tylychko Aug 18 '18 at 22:25
  • 1
    "and despite itself being a valid pointer" -- `nullptr` is not a pointer and cannot be dereferenced. It can be implicitly converted to a pointer type, and after that dereferencing it results in UB, but `nullptr` itself, no. –  Aug 18 '18 at 23:37