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

C++では、シングルトンパターンの実装方法を2つ提供します。

  1. 餓漢式シングルトンパターン
class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // 将构造函数设为私有,禁止外部创建对象
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;

実行時には 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;

使用する際は、Singleton::getInstance() によってシングルトンオブジェクトを取得します。

これらの2つの方法はともにコンストラクタをプライベートにして、外部からのオブジェクト作成を禁止し、静的メンバ変数と静的メンバ関数によってシングルトンオブジェクトの生成と取得を実現しています。餓漢式では、シングルトンオブジェクトはプログラムの起動時に作成され、遅延初回化方式では、シングルトンオブジェクトは初回使用時に作成されます。

bannerAds