skip to Main Content

Firstly, std::nullptr_t is a core language type, so why is it in the std namespace? You don’t see std::char or std::int.

Secondly, where is it in the std namespace? When I right click in Visual Studio to see where it is declared, it says "the symbol nullptr_t is not located in any source file." If std::nullptr_t is not declared in the std namespace, why does code containing std::nullptr_t compile?

EDIT:
This link on microsoft’s website says nullptr is a built in type, and that built in types are not defined in header files.

3

Answers


  1. std::nullptr_t is a core language type

    std::nullptr_t is a fundamental type(aka built in type) as explained here. It is not even a pointer type though it can be implicitly converted to any pointer type. Moreover, it is defined inside header cstddef in namepsace std as quoted below.

    This can be seen from lex.nullptr:

    The pointer literal is the keyword nullptr. It is a prvalue of type std​::​nullptr_­t.
    [ Note: std​::​nullptr_­t is a distinct type that is neither a pointer type nor a pointer-to-member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.
    See [conv.ptr] and [conv.mem].
    — end note
     ]

    From cstddef.syn:

    Header <cstddef> synopsis

    namespace std {
     using nullptr_­t = decltype(nullptr);
    
     //other things here
    }
    
    Login or Signup to reply.
  2. In both libstdc++, libc++, and MSVC’s STL, std::nullptr_t is a typedef for decltype(nullptr).

    So yes, the type is a core language type, but it doesn’t have a name, and the only way to refer to it (without the header) is with decltype(nullptr).

    Login or Signup to reply.
  3. As others have stated, std::nullptr_t is a special type. It is to be distinguished from nullptr itself – which is a value.

    There are some use cases for std::nullptr_t.

    For example function overloads:

    void foo(int*);
    void foo(nullptr_t);
    
    int main() {
        int a = 4;
        int* b = &a;
        foo(b); // will call foo(int*)
        foo(nullptr); // will call foo(nullptr_t)
        b = nullptr;
        foo(b); // will call foo(int*)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search