c++单例模式的实现方法有哪些

在C++中,有几种常见的实现单例模式的方法:

饿汉式单例模式:在程序启动时就创建单例对象,并提供一个公共的访问方法。这种方法的缺点是在程序启动时就创建对象,可能会影响程序的启动速度。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

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

Singleton* Singleton::instance = nullptr;

懒汉式单例模式:在第一次使用时才创建单例对象。这种方法的缺点是需要使用额外的线程同步机制来保证多线程环境下的安全性。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

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

Singleton* Singleton::instance = nullptr;

双重检查锁单例模式:在懒汉式单例模式的基础上加入了双重检查,在多线程环境下保证安全性并减少锁的使用次数。

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;

静态局部变量单例模式:利用C++的静态局部变量特性,在需要时创建单例对象,并确保多线程安全。

class Singleton {
private:
    Singleton() {}

public:
    static Singleton* getInstance() {
        static Singleton instance;
        return &instance;
    }
};
阅读剩余
THE END