implementation safe nullptr

前端 未结 3 988
余生分开走
余生分开走 2021-01-01 00:14

I\'d like to keep my code compilable both on legacy C++ (C++ code using \"NULL\") and new C++11 standard (C++ code using \"nullptr\")

I\'m using GCC, but planning to

相关标签:
3条回答
  • 2021-01-01 00:50

    NULL is a macro that expands to a null pointer constant. It still works just like it used to. Code that has to work with non-C++11 compilers should use NULL.

    0 讨论(0)
  • 2021-01-01 00:54

    You could probably create a "false" my_nullptr of type my_nullptr_t the following way:

    const class my_nullptr_t
    {
        public:
    
            /* Return 0 for any class pointer */
            template<typename T>
            operator T*() const
            {
                return 0;
            }
    
            /* Return 0 for any member pointer */
            template<typename T, typename U>
            operator T U::*() const
            {
                return 0;
            }
    
            /* Safe boolean conversion */
            operator void*() const
            {
                return 0;
            }
    
        private:
    
            /* Not allowed to get the address */
            void operator&() const;
    
    } my_nullptr = {};
    

    This works with C++03 and C++11 and should always be safe, whichever C++11 features are implemented. That solution was actually already discussed in this topic that proposed a version of nullptr_t based on the Official proposal.

    0 讨论(0)
  • 2021-01-01 00:57

    I think following will works:

    #include <cstddef>
    
    #ifndef MY_LIB_NULL
        #ifndef NULL //check for NULL
            #define MY_LIB_NULL nullptr
        #else
            #define MY_LIB_NULL NULL ///use NULL if present
        #endif
    #endif
    

    basically I check for "NULL". wich is a macro and can be checked, until the compiler is shipped with that macro (likely to be), than it's valid using the macro, when compiler will only provides "nullptr" and no longer have NULL then nullptr is used (maybe in a far future, but seems we can happily continue to use NULL!)

    I think that's safer than redefining "nullptr" (like most people trying to do)

    0 讨论(0)
提交回复
热议问题