【问题标题】:What header file needs to be included for using nullptr in g++?在 g++ 中使用 nullptr 需要包含哪些头文件?
【发布时间】:2011-04-14 23:07:00
【问题描述】:

我正在使用 g++ 4.4.1 并想使用 nullptr,但我无法找到需要包含的头文件。它似乎也不是关键字,因为我使用它的尝试被拒绝为

error: 'nullptr' was not declared in this scope

【问题讨论】:

    标签: g++ nullptr


    【解决方案1】:

    GCC 4.4.1 不支持nullptr

    在 GCC 4.6.0 中添加了对 nullptr 的支持: http://gcc.gnu.org/gcc-4.6/changes.html

    改进了对 即将推出的 C++0x ISO C++ 标准, 包括对 nullptr 的支持(谢谢 致 Magnus Fromreide),除了, 不受限制的联合,基于范围的 循环(感谢 Rodrigo Rivas Costa), 隐式删除的函数和 隐式移动构造函数。

    对于早期版本的 GCC,如果您想尝试使用 nullptr,您可以尝试以下 SO 问题中的解决方法:

    Can nullptr be emulated in GCC?

    【讨论】:

    • 因为 GCC 4.6 之前没有 nullptr 你可以使用 "__null"
    • @Trevor Boyd Smith:__null 只是 NULL 在 GCC 上的定义。它nullptr 相同,因为它(显然)具有与NULL 相同的语义。没有理由使用__null
    • 他不是在说g++吗?
    【解决方案2】:

    我建议不要使用上面定义的nullptr,因为它可能很危险。如果你想使用nullptr,下面的说法应该是正确的。

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

    但是,sizeof(nullptr)(如上定义)将不符合此规则。它实际上会评估为sizeof(bad nullptr) = 1

    这是一个正确的实现。

    #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
    

    【讨论】:

    • 如果这对你很重要,也许你也应该考虑确保对齐也是正确的
    • 雅罗斯拉夫,也许你应该考虑写作而不大喊大叫。 :)
    【解决方案3】:

    我使用 -std=c++0x 来启用 gcc 4.6.3 的 nullptr 功能

    【讨论】:

    • 但是 -std=c++0x 在 Gcc 4.4.x 中没有启用 nullptr
    【解决方案4】:

    如果您没有支持 C++11 的最新 gcc,请尝试使用 NULL 而不是 nullptr。

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多