c++visual-studio-2008nullptr

Compile error 'nullptr' undeclared identifier


I'm trying to compile a source with Visual Studio 2008 Express, but I'm getting this error:

Error C2065: 'nullptr' undeclared identifier.

My code:

if (Data == nullptr) {
    show("Data is null");
    return 0;
}

I read on Google that I should upgrade to Visual Studio 2010, but I don't want to do this because of the IntelliSense in Visual Studio 2008. Can this be repaired or replaced?


Solution

  • The error you are getting is because the compiler doesn't recognize the nullptr keyword. This is because nullptr was introduced in a later version of visual studio than the one you are using.

    There's 2 ways you might go about getting this to work in an older version. One idea comes from Scott Meyers c++ book where he suggests creating a header with a class that emulates nullptr like this:

    const // It is a const object...
    class nullptr_t 
    {
      public:
        template<class T>
        inline operator T*() const // convertible to any type of null non-member pointer...
        { return 0; }
    
        template<class C, class T>
        inline operator T C::*() const   // or any type of null member pointer...
        { return 0; }
    
      private:
        void operator&() const;  // Can't take address of nullptr
    
    } nullptr = {};
    

    This way you just need to conditionally include the file based on the version of msvc

    #if _MSC_VER < 1600 //MSVC version <8
         #include "nullptr_emulation.h"
    #endif
    

    This has the advantage of using the same keyword and makes upgrading to a new compiler a fair bit easier (and please do upgrade if you can). If you now compile with a newer compiler then your custom code doesn't get used at all and you are only using the c++ language, I feel as though this is important going forward.

    If you don't want to take that approach you could go with something that emulates the old C style approach (#define NULL ((void *)0)) where you make a macro for NULL like this:

    #define NULL 0
    
    if(data == NULL){
    }
    

    Note that this isn't quite the same as NULL as found in C, for more discussion on that see this question: Why are NULL pointers defined differently in C and C++?

    The downsides to this is that you have to change the source code and it is not typesafe like nullptr. So use this with caution, it can introduce some subtle bugs if you aren't careful and it was these subtle bugs that motivated the development of nullptr in the first place.