代码之家  ›  专栏  ›  技术社区  ›  Ivan Vučica

通过C++中的静态实例将单元格转换为源代码或头文件?

  •  8
  • Ivan Vučica  · 技术社区  · 16 年前

    干杯,

    我在“编程游戏人工智能实例”中遇到了这段代码:

    /* ------------------ MyClass.h -------------------- */
    #ifndef MY_SINGLETON
    #define MY_SINGLETON
    
    class MyClass
    {
    private:
    
      // member data
      int m_iNum;
    
      //constructor is private
      MyClass(){}
    
      //copy ctor and assignment should be private
      MyClass(const MyClass &);
      MyClass& operator=(const MyClass &);
    
    public:
    
      //strictly speaking, the destructor of a singleton should be private but some
      //compilers have problems with this so I've left them as public in all the
      //examples in this book
      ~MyClass();
    
      //methods
      int GetVal()const{return m_iNum;}
      static MyClass* Instance();
    };
    
    #endif
    
    /* -------------------- MyClass.cpp ------------------- */
    
    //this must reside in the cpp file; otherwise, an instance will be created
    //for every file in which the header is included
    MyClass* MyClass::Instance()
    {
      static MyClass instance;
    
      return &instance;
    }
    

    我对作者的事实陈述感到困惑,即头中的函数中静态声明的变量将导致声明多个独立的静态变量。 instance . 我不认为我在通常的 getInstance() 函数,我经常将其放入头中(除了我喜欢使用指针并在第一次使用时初始化singleton)。我在用GCC做我的工作。

    那么标准怎么说呢?不兼容的编译器怎么说?作者的语句是否正确?如果正确,您能否命名一些编译器,这些编译器将在以下情况下创建多个实例: 获取实例() 是否在标题中声明?

    2 回复  |  直到 16 年前
        1
  •  10
  •   AProgrammer    16 年前

    在C++中,没有任何阻止内联函数具有静态变量,编译器必须安排使这些变量在所有翻译单元之间通用(就像它必须为模板实例化静态类成员和静态函数变量这样做)。7.1.2/4

    static 变量中的 extern inline 函数始终引用同一对象。

    注意,在C语言中,内联函数不能有静态变量(也不能引用具有内部链接的对象)。

        2
  •  1
  •   quamrana Ryuzaki L    16 年前

    我尝试过用VS2008发布的代码,有四种方法,但静态实例似乎没有问题。 MyClass 里面 MyClass::Instance() .

    1. Instance() 定义在 myclass.cpp:这是正常的方式 一切都很好。
    2. () 仅在 类声明。这就是 选择,一切都很好。
    3. () 定义 inline 在课堂之外,但在标题中 一切都很好。
    4. 为3。但是没有 内联的 和 链接器说有多种定义 ()

    我认为这本书的作者与4有关。并且知道MyClass的静态实例将在编译和链接的程序中得到处理。