Search code examples
c++gccc++11unique-ptrnullptr

unique_ptr, nullptr and supporting gcc 4.5.x and 4.6.x


I am working on a library with two different end users one of which is using gcc 4.5.3 and the other just moved to gcc 4.6.3. The library uses the new C++11 smart pointers (in particular unique_ptr) and compiles fine on gcc 4.5.3. However, between those two versions gcc began supporting nullptr so the API of unique_ptr changed to match the standard more closely. In doing so now the following code went from fine to ambiguous

unique_ptr up( new int( 30 ) );
...
if( up == 0 ) // ambiguous call now to unique_ptr(int) for 0

Is there a clean (viz., next sentence) way to change the if statement above so that it works both with and without nullptr? I'd like to avoid a configure check and then a macro like the following (which I think will work) if possible

#if defined NULLPOINTER_AVAILABLE
  #define NULLPTR (nullptr)
#else
  #define NULLPTR (0)
#endif

or is this the only way to get the behavior I am looking?


Solution

  • What errors did you hit?

    #include <iostream>
    #include <memory>
    int main() {
     using namespace std;
     unique_ptr<int> up( new int( 30 ) );
     if (up == 0)
         cout << "nullptr!\n";
     else cout << "bam!\n";
    }
    

    compiles fine with with g++ -std=c++0x -Wall nullptr.cpp -o nullptr (gcc 4.6.2).

    Also, go through N2431 paper by Stroustrup and Sutter on nullptrwhere a similar usage (comparison with 0) is explicitly listed in one of the examples.