开发者

Can nullptr be emulated in gcc?

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. My code needs to run on both (but doesn't have to compile with other co开发者_StackOverflowmpilers).

Is there a way to "emulate" it? Something like:

#define nullptr NULL

(That obviously wouldn't work well at all, it's just to show what I mean.)


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 looks like gcc supports nullptr as of 4.6.


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 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'


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜