What exactly is nullptr?

前端 未结 14 2414
无人及你
无人及你 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:47

    Let me first give you an implementation of unsophisticated nullptr_t

    struct nullptr_t 
    {
        void operator&() const = delete;  // Can't take address of nullptr
    
        template
        inline operator T*() const { return 0; }
    
        template
        inline operator T C::*() const { return 0; }
    };
    
    nullptr_t nullptr;
    

    nullptr is a subtle example of Return Type Resolver idiom to automatically deduce a null pointer of the correct type depending upon the type of the instance it is assigning to.

    int *ptr = nullptr;                // OK
    void (C::*method_ptr)() = nullptr; // OK
    
    • As you can above, when nullptr is being assigned to an integer pointer, a int type instantiation of the templatized conversion function is created. And same goes for method pointers too.
    • This way by leveraging template functionality, we are actually creating the appropriate type of null pointer every time we do, a new type assignment.
    • As nullptr is an integer literal with value zero, you can not able to use its address which we accomplished by deleting & operator.

    Why do we need nullptr in the first place?

    • You see traditional NULL has some issue with it as below:

    1️⃣ Implicit conversion

    char *str = NULL; // Implicit conversion from void * to char *
    int i = NULL;     // OK, but `i` is not pointer type
    
    

    2️⃣ Function calling ambiguity

    void func(int) {}
    void func(int*){}
    void func(bool){}
    
    func(NULL);     // Which one to call?
    
    
    • Compilation produces the following error:
    error: call to 'func' is ambiguous
        func(NULL);
        ^~~~
    note: candidate function void func(bool){}
                                  ^
    note: candidate function void func(int*){}
                                  ^
    note: candidate function void func(int){}
                                  ^
    1 error generated.
    compiler exit status 1
    
    

    3️⃣ Constructor overload

    struct String
    {
        String(uint32_t)    {   /* size of string */    }
        String(const char*) {       /* string */        }
    };
    
    String s1( NULL );
    String s2( 5 );
    
    
    • In such cases, you need explicit cast (i.e., String s((char*)0)).

提交回复
热议问题