【1】C++设计模式之【单例模式】

发布于:2024-04-14 ⋅ 阅读:(126) ⋅ 点赞:(0)

单例模式在C++中的实现方式有以下几种:

  1. 懒汉式(线程不安全)
  2. 饿汉式(线程安全)
  3. 双检锁/双重校验锁(DCL,线程安全)
  4. 静态局部变量(线程安全)
  5. C++11版本(线程安全)

下面分别给出这五种实现方式的代码示例和解释。

懒汉式(线程不安全)

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

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

Singleton* Singleton::instance = nullptr;

解释:这种方式是在第一次调用getInstance()方法时才创建实例,但是这种方式在多线程环境下是不安全的,可能会出现多个实例。

饿汉式(线程安全)

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

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

Singleton* Singleton::instance = new Singleton();

双检锁/双重校验锁(DCL,线程安全)

#include <mutex>

class Singleton {
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            std::unique_lock<std::mutex> lock(mutex);
            if (instance == nullptr) {
                instance = new Singleton();
            }
        }
        return instance;
    }

private:
    Singleton() {}
    static Singleton* instance;
    static std::mutex mutex;
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;

解释:这种方式是在第一次检查实例是否为空时加锁,再次检查实例是否为空时不加锁,这样可以减少锁的开销,提高性能。

静态局部变量(线程安全)

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

private:
    Singleton() {}
};

解释:这种方式利用了C++11的特性,将实例定义为静态局部变量,这样在程序结束时会自动销毁实例,避免了资源泄露。同时,这种方式也是线程安全的。

C++11版本(线程安全)

#include <mutex>

class Singleton {
public:
    static Singleton& getInstance() {
        std::call_once(initInstanceFlag, &Singleton::initInstance);
        return *instance;
    }

private:
    Singleton() {}
    static void initInstance() {
        instance = new Singleton();
    }
    static Singleton* instance;
    static std::once_flag initInstanceFlag;
};

Singleton* Singleton::instance = nullptr;
std::once_flag Singleton::initInstanceFlag;

解释:这种方式利用了C++11的std::call_once和std::once_flag来实现线程安全的单例模式,确保只初始化一次实例。


网站公告

今日签到

点亮在社区的每一天
去签到