温馨提示×

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

c++
小亿
74
2023-10-31 12:08:04
栏目: 编程语言

在C++中,可以通过以下几种方式来实现单例模式:

  1. 饿汉式单例模式(Eager Initialization): 在类定义中静态地创建一个单例对象,保证了在程序运行期间只会创建一个实例。这种方式的缺点是无法进行延迟加载,即使程序不需要使用该单例对象也会被创建。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

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

Singleton* Singleton::instance = nullptr;
  1. 懒汉式单例模式(Lazy Initialization): 在第一次使用该单例对象时才创建实例。这种方式可以实现延迟加载,但需要考虑线程安全问题。
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

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

Singleton* Singleton::instance = nullptr;
  1. 双重检查锁定(Double-checked Locking): 在懒汉式的基础上增加了同步锁,解决了线程安全问题,同时也保持了延迟加载的特性。
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. 静态局部变量(Local Static): 利用局部静态变量的特性,可以在函数内部定义一个静态局部变量,保证了只有在第一次调用该函数时才实例化单例对象。这种方式也是线程安全的。
class Singleton {
private:
    Singleton() {}

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

这些是常见的几种单例模式的实现方式,选择哪种方式取决于具体的需求和场景。

0