Search code examples
c++c++11overridingfinalnullptr

implementation safe nullptr


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 recompile the whole codebase also for VS when I'll finish most important things.

Should I expect both GCC and VS will do something like

#define NULL nullptr

Or Is better I'll do that myself (using of course a different name, where MY_LIB will be replaced by my library suffix)?

#ifndef nullptr
    #define MY_LIB_NULL NULL
#else
    #define MY_LIB_NULL nullptr
#endif

What I want to achieve is code that compiles regardless of wich C++11 features have been implemented or not (and since i'm not using templates, there are very few of them).

For example the keywords "override" and "final" are already done.

MY_LIB_OVERRIDE //macro, defines to "override" if c++11 is present.
MY_LIB_FINAL    //macro, defines to "final" if c++11 is present.

I'm asking the question because I know the "nullptr" question is a bit strange, so maybe just doing the same I already did for override and final, is wrong. Needs opinions about that. Any help is wellcome.


Solution

  • 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.