C++でSingletonパターンを実装する方法は何ですか。

C++でSingletonパターンを実装する方法はいくつかあります:

  1. プログラム起動時にシングルトンオブジェクトを作成し、グローバルなアクセスポイントを提供する饑餓式単一インスタンスパターン。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

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

Singleton* Singleton::instance = new Singleton();
  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. 初めてアクセスされた場合にのみシングルトンオブジェクトを作成し、スレッドセーフを確保するために二重チェックロックを使用したシングルトンパターン。
#include <mutex>

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;

これらはSingletonパターンを実装する一般的な方法であり、具体的な要求やスレッドセーフ性に合わせて選択することができます。

bannerAds