干杯,
我在“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;
}
我对作者的事实声明感到困惑,即 header 中函数内的静态声明变量将导致声明多个单独的静态变量 instance
。我不认为我在我经常将其放入 header 中的 getInstance()
函数的常用实现中看到过这种行为(除了我喜欢玩指针并在首次使用时初始化单例)。我在工作中使用 GCC。
那么标准是怎么说的呢?不兼容的编译器怎么说?作者的陈述是否正确?如果是这样,如果在 header 中声明了 getInstance()
,您能说出一些会创建多个实例的编译器吗?
最佳答案
在 C++ 中,没有什么可以阻止内联函数拥有静态变量,并且编译器必须安排使该变量在所有翻译单元之间通用(就像它必须为模板实例化静态类成员和静态函数变量那样做)。 7.1.2/4
A
static
variable in anextern inline
function always refer to the same object.
请注意,在 C 中,内联函数不能有静态变量(也不能引用具有内部链接的对象)。
关于c++ - 通过 C++ 中的静态实例的单例——进入源文件或头文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1389337/