c++ 单例模式多种写法

本文介绍了两种单例模式实现方式:饿汉模式和懒汉模式。饿汉模式在类加载时就创建单例,线程安全但会占用资源。懒汉模式则在第一次调用时创建单例,线程安全版本通过`std::call_once`保证了线程安全。这两种模式各有优缺点,适用于不同的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

饿汉模式:

缺点:不使用的时候占用资源,不支持向单例构造函数传参;
优点:不存在多线程的实例化,线程安全,提前加载单例 节省运行时间;

template <class T>
class Singleton
{
private:
	static T* _instance;
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

public:
    static T* instance() { return _instance; }
};
template <class T>
T* Singleton<T>::_instance = new T();

懒汉模式

1、普通版:

template <class T>
class Singleton
{
private:
	static T* _instance;
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

public:
    static T* instance()
    {
        if (!_instance)
        {
            _instance = new T();
        }
        return _instance;
    }
};
template <class T>
T* Singleton<T>::_instance = NULL;

2、线程安全版:

template<class T>
class Singleton {
public:
    template <typename... Args>
    static T* instance(Args&& ..args) {
        std::call_once(_flag, [&]() {_instance = new T(std::forward<Args>(args)...); });
        return _instance;
    }
private:
    static T* _instance;
    static std::once_flag _flag;
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton& single) = delete;
    const Singleton& operator=(const Singleton& single) = delete;
};
template <class T>
T* Singleton<T>::_instance = NULL;
template <class T>
std::once_flag Singleton<T>::_flag;

代码转载来源:单例模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值