开发者

What header file needs to be included for using nullptr in g++?

I am using开发者_如何学Go g++ 4.4.1 and want to use nullptr, but I am not being able to find which header file is required to be included. It does not seem to be keyword either, because my attempt to use it is rejected as

error: 'nullptr' was not declared in this scope


GCC 4.4.1 does not support nullptr.

Support for nullptr was added in GCC 4.6.0: http://gcc.gnu.org/gcc-4.6/changes.html

Improved experimental support for the upcoming C++0x ISO C++ standard, including support for nullptr (thanks to Magnus Fromreide), noexcept, unrestricted unions, range-based for loops (thanks to Rodrigo Rivas Costa), implicitly deleted functions and implicit move constructors.

For earlier versions of GCC, if you want to experiment with nullptr you can try the workaround in this SO question:

Can nullptr be emulated in GCC?


I would recommend not using nullptr as defined above, because it can be dangerous. If you want to use nullptr the following statement should be true.

sizeof(nullptr) == sizeof(void*) == sizeof(any pointer)

However, sizeof(nullptr) (as defined above) will not comply to this rule. It will actually evaluate to sizeof(bad nullptr) = 1.

This is a correct implementation.

#pragma once

namespace std
{
    //based on SC22/WG21/N2431 = J16/07-0301
    struct nullptr_t
    {
        template<typename any> operator any * () const
    {
        return 0;
    }
    template<class any, typename T> operator T any:: * () const
    {
        return 0;
    }

#ifdef _MSC_VER
    struct pad {};
    pad __[sizeof(void*)/sizeof(pad)];
#else
    char __[sizeof(void*)];
#endif
private:
    //  nullptr_t();// {}
    //  nullptr_t(const nullptr_t&);
    //  void operator = (const nullptr_t&);
    void operator &() const;
    template<typename any> void operator +(any) const
    {
        /*I Love MSVC 2005!*/
    }
    template<typename any> void operator -(any) const
    {
        /*I Love MSVC 2005!*/
    }
    };
static const nullptr_t __nullptr = {};
}

#ifndef nullptr
#define nullptr std::__nullptr
#endif


I use -std=c++0x to enable the nullptr feature with gcc 4.6.3


If you don't have the latest gcc which supports C++11 , try using NULL instead of nullptr.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜