C++单例模式
提供唯一一个全局对象,每次访问时返回同一个对象实例。
实现步骤:
-
提供一个全局的public函数,用来访问实例。
-
构造函数private,避免外部创建实例。
-
合理的存储方式来保证唯一性(例如使用静态变量来保存指针或引用)。
-
懒汉式单例模式实现(线程不安全)
懒汉式,就是等到需要的时候在创建,如下代码所示即在第一次调用GetInstance() 函数时创建实例。
template <typename T> class Singleton { public: static T* GetInstance() { if (instance_ == nullptr) { instance_ = new T; } return instance_; } virtual ~Singleton(){} protected: static volatile T* instance_; Singleton(){} Singleton (const Singleton &); Singleton& operator = (const Singleton &); }; template <typename T> T* Singleton<T>::instance_ = nullptr;
-
饿汉式单例模式实现(线程安全)- 静态局部变量
饿汉式,就是一开始就创建好了,在每次调用GetInstance() 直接返回创建好的实例。
使用C++静态局部变量,在C++11标准中,要求局部静态变量初始化具有线程安全性。在C++标准中,是这样描述的(在标准草案的6.7节中):
such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
template <typename T> class Singleton { public: static T* GetInstance() { static T instance_; return &instance_; } virtual ~Singleton(){} protected: Singleton(){} Singleton (const Singleton &); Singleton& operator = (const Singleton &); };
-
懒汉式单例模式实现(线程安全)- 锁
使用C++ < mutex >库中提供的mutex互斥锁 (C++11) 。
#include <mutex> template <typename T> class Singleton { public: static T* GetInstance() { if (instance_ == nullptr) { std::lock_guard<std::mutex> lock(mutex_); if (instance_ == nullptr) { instance_ = new T; } } return instance_; } virtual ~Singleton(){} protected: static std::mutex mutex_; static volatile T* instance_; Singleton(){} Singleton (const Singleton &); Singleton& operator = (const Singleton &); }; template <typename T> T* Singleton<T>::instance_ = nullptr; template <typename T> std::mutex Singleton<T>::mutex_;
-
懒汉式单例模式实现(线程安全)- 锁,原子变量
使用C++ < mutex> 库中提供的mutex互斥锁。
使用C++ < atomic> 中的原子操作以及memory_order。#include <mutex> #include <atomic> template <typename T> class Singleton { public: static T* GetInstance() { T* tmp = instance_.load(std::memory_order::memory_order_acquire); if (tmp == nullptr) { std::lock_guard<std::mutex> lock(mutex_); tmp = instance_.load(std::memory_order::memory_order_relaxed); if (instance_ == nullptr) { tmp = new T; instance_.store(tmp, std::memory_order::memory_order_release); } } return instance_; } virtual ~Singleton(){} protected: static std::mutex mutex_; static std::atomic<T*> instance_; Singleton(){} Singleton (const Singleton &); Singleton& operator = (const Singleton &); }; template <typename T> std::atomic<T*> Singleton<T>::instance_ = nullptr; template <typename T> std::mutex Singleton<T>::mutex_;