Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does nullptr not require header while nullptr_t does

Tags:

c++

c++11

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?

like image 343
rohitt Avatar asked Dec 02 '20 11:12

rohitt


People also ask

Can I use nullptr instead of null?

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.

How does nullptr work C++?

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.

Does nullptr return false?

- 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.

How do I check if a pointer is nullptr?

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.


2 Answers

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_­t is a synonym for the type of a nullptr expression, 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.

like image 196
dfrib Avatar answered Oct 11 '22 14:10

dfrib


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.

like image 27
Daniel Langr Avatar answered Oct 11 '22 13:10

Daniel Langr