单例通过C++中的静态实例 - 进入源文件或进入头文件?

Iva*_*ica 8 c++ compiler-construction singleton

干杯,

我在"Programming Game AI by Example"中遇到了这段代码:

/* ------------------ 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;
}
Run Code Online (Sandbox Code Playgroud)

我对作者的事实陈述感到困惑,在标题中的函数内部静态声明的变量将导致声明多个独立的静态变量instance.我不认为我在我常用的getInstance()函数实现中看到过这种行为,我经常将它放入标题中(除了我喜欢在第一次使用时使用指针和初始化单例).我正在使用GCC来完成我的工作.

那标准说的是什么?不合规的编译器说什么?作者的陈述是否正确,如果是这样,您是否可以命名一些编译器,如果getInstance()在标题中声明的话会创建多个实例?

APr*_*mer 10

在C++中,没有什么能阻止内联函数具有静态变量,并且编译器必须安排在所有转换单元之间使该变量通用(就像它必须为模板实例化静态类成员和静态函数变量一样).7.1.2/4

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

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