I saw that nullptr
was implemented in Visual Studio 2010. I like the concept and want to start using it as soon as possible; however GCC does not support it yet
The Official proposal has a workaround -
const // this is a const object...
class {
public:
template<class T> // convertible to any type
operator T*() const // of null non-member
{ return 0; } // pointer...
template<class C, class T> // or any type of null
operator T C::*() const // member pointer...
{ return 0; }
private:
void operator&() const; // whose address can't be taken
} nullptr = {}; // and whose name is nullptr
It's most likely you forgot -std=c++0x . My Mingw version of gcc is 4.6.1/4.7.1, both support nullptr well.
According to description in "The c++ standard library, a tutorial and reference, 2nd", nullptr is a keyword, can automatically convert to each pointer type but not integer type, this overcome the drawback of NULL, which is ambiguous to the following overload function: void f(int ); void f(void *);
f(NULL); // Ambiguous f(nullptr); // OK
Test this feature in VC2010 shows that the MSDN document conflicts with the actual compiler, the document said:
The nullptr keyword is not a type and is not supported for use with:
sizeof
typeid
throw nullptr
Actually in VC2010, all of the above operator/expression is legal. sizeof(nullptr) result 4. typeid.name() result std::nullptr_t, and throw nullptr can be caught by "const void *" and "void *"(and other pointer types).
While gcc(4.7.1) looks more rigid about nullptr, throw nullptr cannot be caught by "void *", can be caught by '...'
Also, gcc (actually g++) has had an extension __null for years. This was counted as industry implementation experience when the nullptr proposal came out.
The __null extension can detect special cases and warn about them such as accidentally passing NULL to a bool parameter, when it was intended to be passed to a pointer parameter (changes made to a function, forgot to adapt the call side).
Of course this isn't portable. The template solution above is portable.
It looks like gcc supports nullptr as of 4.6.
It looks by gcc 4.6.1 (Ubuntu 11.11 oneiric), nullptr has been added.
A quick, recursive sed find-and-replace on my hpp/cpp files worked fine for me:
find . -name "*.[hc]pp" | xargs sed -i 's/NULL/nullptr/g'