乾杯は、C++の静的インスタンスを介したシングルトン - ソースファイルまたはヘッダーファイル?
私は「例によるプログラミングゲームAI」でこのコードの塊に走った:
/* ------------------ 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()
の機能でこの動作を見たことはないと思います(ただし、ポインタを使って遊んで最初の使用時にシングルトンを初期化するのを除いて)。私は自分の仕事にGCCを使用しています。
だから、規格は何を言っているのですか?非準拠のコンパイラは何を言いますか?著者のステートメントが正しいかどうか、もしそうなら、getInstance()
がヘッダーで宣言されていれば、複数のインスタンスを作成するコンパイラの名前を付けることができますか?
シングルトンを実装する方法と、C++のスレッドセーフティについての素晴らしい説明は、このホワイトペーパーで見つけることができます。 http://www.aristeia.com/Papers/DDJ%5FJul%5FAug%5F2004%5Frevised .pdf –