What exactly is nullptr?

前端 未结 14 2690
无人及你
无人及你 2020-11-22 01:12

We now have C++11 with many new features. An interesting and confusing one (at least for me) is the new nullptr.

Well, no need anymore for the nasty mac

14条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:48

    According to cppreference, nullptr is a keyword that:

    denotes the pointer literal. It is a prvalue of type std::nullptr_t. There exist implicit conversions from nullptr to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of type std::nullptr_t as well as the macro NULL.

    nullptr will convert implicitly to any pointer type but not to an integer. NULL, however, is a macro and it is an implementation-defined null pointer constant. It's often defined like this:

    #define NULL 0
    

    i.e. an integer.

    Hence:

    int i = NULL;     //OK
    int i = nullptr;  //error
    int* p = NULL;    //OK
    int* p = nullptr; //OK
    

    nullptr can avoid ambiguity when you have two function overloads like this:

    void func(int x);   //1)
    void func(int* x);  //2)
    

    func(NULL) calls 1) because NULL is an integer. func(nullptr) calls 2) because nullptr is not an integer and converts implicitly to any pointer type.

    Advantages of using nulptr:

    • avoid ambiguity between function overloads
    • enables you to do template specialization
    • more secure, intuitive and expressive code, e.g. if (ptr == nullptr) instead of if (ptr == 0)

提交回复
热议问题