singleton(单例模式)

一个线程安全的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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 动机 有些情况下,一个类只能有一个实例是很重要的。比如说,在操作系统中只能有一个窗口管理器的(文件系统或打印机程序...
    holysu阅读 1,300评论 0 0
  • Singleton模式的经典意义为:在该实例不存在的情况下,可以通过一个方法创建一个类来实现创建一个类的新的实例;...
    悠扬前奏阅读 245评论 0 0
  • 2017中秋 举杯邀月相思影, 月下成行影无踪。 离愁断肠伊人泪, 望断天涯水一方。
    星落凡尘007阅读 330评论 0 0
  • 因为最近有一个项目需要调用手机拍照功能,然后将图片显示在ImageView中。因为还是小白,所以花了一点时间去研究...
    欢乐的乐阅读 2,187评论 0 6
  • 祖母老了,背驼耳背,身子也萎缩得愈加矮小,整个人就仿佛一段岁月的弧,一只煮熟的虾。按理说,像祖母这样年愈八旬的老人...
    云问雨阅读 319评论 0 5