美文网首页
singleton(单例模式)

singleton(单例模式)

作者: yandaren | 来源:发表于2017-03-01 20:43 被阅读0次

一个线程安全的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;

相关文章

网友评论

      本文标题:singleton(单例模式)

      本文链接:https://www.haomeiwen.com/subject/euucgttx.html