最近、C++ のシングルトン デザイン パターンの実現/実装に出会いました。これは次のようになります (実際の例から採用しました)。
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
この宣言から、インスタンス フィールドがヒープ上で初期化されていることがわかります。つまり、メモリ割り当てがあるということです。私にとってまったく不明なのは、メモリがいつ解放されるのかということです。それとも、バグやメモリ リークがあるのでしょうか。実装に問題があるようです。
私の主な質問は、それをどのように正しく実装するかということです。
ベストアンサー1
2008 年に、私は遅延評価、破棄保証、技術的にはスレッドセーフではないシングルトン デザイン パターンの C++98 実装を提供しました。
誰か C++ のシングルトンのサンプルを提供してもらえますか?
これは遅延評価され、正しく破棄され、そしてスレッドセーフ。
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
シングルトンを使用する場合については、この記事を参照してください: (頻繁ではありません)
シングルトン:どのように使うべきか
初期化の順序と対処方法については、次の 2 つの記事を参照してください。
静的変数の初期化順序
C++ の静的初期化順序の問題を見つける
ライフタイムについて説明しているこの記事を参照してください:
C++ 関数内の静的変数の有効期間はどれくらいですか?
シングルトンに対するスレッドの影響について説明しているこの記事を参照してください。
GetInstance メソッドの静的変数として宣言されたシングルトン インスタンスは、スレッドセーフですか?
ダブルチェックロックが C++ で機能しない理由については、この記事を参照してください。
C++ プログラマーが知っておくべき一般的な未定義の動作とは何ですか?
ドブス博士: C++ と二重チェックロックの危険性: パート I