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

本文介绍了C++中实现单例模式的五种方式:懒汉式、饿汉式、双检锁/双重校验锁(DCL)、静态局部变量和C++11版本,并详细解释了每种方式的特点和线程安全性。
摘要由CSDN通过智能技术生成

单例模式在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来实现线程安全的单例模式,确保只初始化一次实例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值