singleton(单例模式)

一个线程安全的singleton implement

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

#include 

template
class Singleton
{
public:
    static Type* get()
    {
        if( m_instance == nullptr)
        {
            std::lock_guard lock(m_mtx);
            
            if( m_instance == nullptr)
            {
                Type* newval = new Type();
                
                m_instance = reinterpret_cast(newval);
            }
        }
        
        return reinterpret_cast(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
void* Singleton::m_instance = nullptr;

template
std::mutex Singleton::m_mtx;

你可能感兴趣的:(singleton(单例模式))