带模板的线程安全单例模式
代码如下,
#pragma once
#include <atomic>
#include <mutex>
template<typename T>
class Singleton
{
private:
Singleton();
Singleton(Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator = (Singleton const&) = delete;
public:
// 方案一:太慢了
//static T* getInstance() {
// std::lock_guard<std::mutex> lock(mutex_);
// T* ptrSingleton = singleton_.load();
// if (nullptr == ptrSingleton) {
// T* singleton = new T();
// singleton_.store(singleton);
// ptrSingleton = singleton_.load();
// }
// return ptrSingleton;
//}
// 方案二:略显复杂
//static T* getInstance() {
// T* ptrSingleto = singleton_.load(std::memory_order_relaxed);
// //acquire fence可以防止fence后的内存操作重排到fence前的任意load之前,即阻止loadload重排和loadstor