C++でシングルトンパターンを実装する方法

C++では、次のような方法でシングルトンパターンを実装できます。

  1. 初期化の段階でインスタンスを生成するイーガーローディング
class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有构造函数,防止类外实例化对象
public:
static Singleton* getInstance() {
return instance;
}
};
Singleton* Singleton::instance = new Singleton();

この実装では、プログラム起動時にシングルトンオブジェクトが生成されるため「餓漢」と呼ばれ、getInstance()メソッドの呼び出し時に予め生成されたインスタンスを返却します。

  1. 遅延初期化
class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有构造函数,防止类外实例化对象
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;

インスタンスはgetInstance()メソッドが初めて呼び出されたときに生成されるため、「遅延初期化」と呼ばれます。インスタンス作成の有無はinstanceがnullptrか否かで判断し、nullptrであれば生成し、そうでなければインスタンスを返します。

  1. 二重ロックチェック
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() {} // 私有构造函数,防止类外实例化对象
public:
static Singleton* getInstance() {
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

この実装では、二重確認ロックを使用してスレッドセーフティが保証されます。最初にインスタンスがヌルかどうかを判定し、もしそうならロックし、再度インスタンスがヌルかどうかを判定します。そうであればインスタンスを作成します。std::mutexを使用してスレッド同調を実現します。

上記は、よく使われるシングルトンパターンの実装方法です。どの方法を選択するかは、実際のニーズと状況に応じて異なります。

bannerAds