nullptr_t is the type for nullptr. When I use nullptr_t, I have to use the header file <cstddef> but why isn't it required when using the nullptr keyword alone?
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.
The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object. Use nullptr with either managed or native code.
- In the context of a direct-initialization, a bool object may be initialized from a prvalue of type std::nullptr_t, including nullptr. The resulting value is false.
To test if a pointer is a nullptr , you can compare it by using the = and the != operator. This is useful when we are using pointers to access objects.
As per [lex.key]/1, nullptr is a keyword:
The identifiers shown in Table 5 are reserved for use as keywords (that is, they are unconditionally treated as keywords in phase 7) [...]
[tab:lex.key]: ...
nullptr
Whereas std::nullptr_t is an alias declaration defined by the standard. Particularly, as of [cstddef.syn], is is defined as the type of the a nullptr expression:
Header
<cstddef>synopsis...
using nullptr_t = decltype(nullptr);
as specified in [support.types.nullptr]/1:
The type
nullptr_tis a synonym for the type of anullptrexpression, and it has the characteristics described in [basic.fundamental] and [conv.ptr].
Thus, to make use of std::nullptr_t, you need to include the <cstddef> header, but you can likewise use decltype(nullptr) if you simply want the same underlying type but without using the std::nullptr_t alias.
nullptr is a keyword, std::nullptr_t is a type defined by the C++ Stadnard library. Keywords are not introduced by header files, they are "wired" in the compiler itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With