What exactly is nullptr?

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

    Also, do you have another example (beside the Wikipedia one) where nullptr is superior to good old 0?

    Yes. It's also a (simplified) real-world example that occurred in our production code. It only stood out because gcc was able to issue a warning when crosscompiling to a platform with different register width (still not sure exactly why only when crosscompiling from x86_64 to x86, warns warning: converting to non-pointer type 'int' from NULL):

    Consider this code (C++03):

    #include 
    
    struct B {};
    
    struct A
    {
        operator B*() {return 0;}
        operator bool() {return true;}
    };
    
    int main()
    {
        A a;
        B* pb = 0;
        typedef void* null_ptr_t;
        null_ptr_t null = 0;
    
        std::cout << "(a == pb): " << (a == pb) << std::endl;
        std::cout << "(a == 0): " << (a == 0) << std::endl; // no warning
        std::cout << "(a == NULL): " << (a == NULL) << std::endl; // warns sometimes
        std::cout << "(a == null): " << (a == null) << std::endl;
    }
    

    It yields this output:

    (a == pb): 1
    (a == 0): 0
    (a == NULL): 0
    (a == null): 1
    

提交回复
热议问题