#pragma once #include <atomic> #include <mutex> namespace sinftech { template<typename T> class Singleton { public: static T* get() { T* tmp = _instance.load(std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); if(tmp == nullptr) { std::lock_guard<std::mutex> lock(_mutex); tmp = _instance.load(std::memory_order_relaxed); if(tmp == nullptr) { tmp = new T; std::atomic_thread_fence(std::memory_order_release); _instance.store(tmp, std::memory_order_relaxed); } } return tmp; } static void destroy() { T* tmp = _instance.exchange(nullptr, std::memory_order_relaxed); delete tmp; } private: Singleton() {} ~Singleton() {} static std::atomic<T*> _instance; static std::mutex _mutex; }; template<typename T> std::atomic<T*> Singleton<T>::_instance; template<typename T> std::mutex Singleton<T>::_mutex; }//namespace sinftech