C++でのシングルトンパターンの実装方法は何がありますか?

C++では、シングルトンパターンを実装するための一般的な方法がいくつかあります。

  1. プレイヤーのようなシングルトンパターンは、プログラムの開始時にシングルトンオブジェクトを作成し、共通のアクセスメソッドを提供します。この方法の欠点は、プログラムの開始時にオブジェクトを作成するため、プログラムの起動速度に影響を与える可能性があることです。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;
  1. 一度使われるまで、怠け者方式によるシングルトンパターンはシングルトンオブジェクトを生成します。この方法の欠点は、マルチスレッド環境の安全性を確保するために追加のスレッド同期メカニズムを使用する必要があることです。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = 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;
  1. C++の静的ローカル変数を使用して、必要な時にシングルトンオブジェクトを作成し、マルチスレッドセーフを確保する静的ローカル変数のシングルトンパターン。
class Singleton {
private:
    Singleton() {}

public:
    static Singleton* getInstance() {
        static Singleton instance;
        return &instance;
    }
};
bannerAds