singleton(单例模式)

2017-03-01  本文已影响0人  yandaren

一个线程安全的singleton implement

/** 
 * a thread safe singleton pattern, use double-checked locking pattern
 */

#include <mutex>

template<typename Type>
class Singleton
{
public:
    static Type* get()
    {
        if( m_instance == nullptr)
        {
            std::lock_guard<std::mutex> lock(m_mtx);
            
            if( m_instance == nullptr)
            {
                Type* newval = new Type();
                
                m_instance = reinterpret_cast<void*>(newval);
            }
        }
        
        return reinterpret_cast<Type*>(m_instance);
    }
    
    static Type& instance()
    {
        return *get();
    }
    
    Type& operator * ()
    {
        return *get();
    }
    
    Type* operator -> ()
    {
        return get();
    }
    
protected:
    static void* m_instance;
    static std::mutex m_mtx;
}

template<typename Type>
void* Singleton<Type>::m_instance = nullptr;

template<typename Type>
std::mutex Singleton<Type>::m_mtx;
上一篇 下一篇

猜你喜欢

热点阅读