What exactly is nullptr?

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

    When you have a function that can receive pointers to more than one type, calling it with NULL is ambiguous. The way this is worked around now is very hacky by accepting an int and assuming it's NULL.

    template 
    class ptr {
        T* p_;
        public:
            ptr(T* p) : p_(p) {}
    
            template 
            ptr(U* u) : p_(dynamic_cast(u)) { }
    
            // Without this ptr p(NULL) would be ambiguous
            ptr(int null) : p_(NULL)  { assert(null == NULL); }
    };
    

    In C++11 you would be able to overload on nullptr_t so that ptr p(42); would be a compile-time error rather than a run-time assert.

    ptr(std::nullptr_t) : p_(nullptr)  {  }
    

提交回复
热议问题