单例设计模式(懒汉模式,饿汉模式)c++

  


class 单例   {   公众://获取唯一实例的接口函数   static 单*,GetInstance ()   {//双重检查,提高效率,避免高并发场景下每次获取实例对象都进行加锁   if  (_sInstance ==, NULL)   {   std:: lock_guard,锁(_mtx);      if  (_sInstance ==, NULL)   {   单例*,tmp =, new 单;   MemoryBarrier();,//内存栅栏,防止编译器优化   _sInstance =, tmp;   }   }      return , _sInstance;   }      static  void  DelInstance ()   {   if  (_sInstance)   {   delete  _sInstance;   时间=_sInstance 零;   }   }      void  Print ()   {   std:: cout  & lt; & lt;, _data  & lt; & lt;, std:: endl;   }      私人://构造函数定义为私有,限制只能在类内实例化对象   单例()   :_data (10)   {}//防拷贝   单例(const  Singleton&);   Singleton&,操作符=(const  Singleton&);      私人:   static  std:: mutex  _mtx,//保证线程安全的互斥锁   static 单*,_sInstance;,//指向实例的指针定义为静态私有,这样定义静态成员获取对象实例   int  _data,//单例类里面的数据   };


/*方式一*/class 单例   {   公众:   static 单*,GetInstance ()   {   static  Singleton  sInstance;   return , sInstance;   }      void  Print ()   {   std:: cout  & lt; & lt;, _data  & lt; & lt;, std:: endl;   }      私人:   单例()   :_data (10)   {}      单例(const  Singleton&);   Singleton&,操作符=(const  Singleton&);      私人:   static 单*,_sInstance;   int  _data;   };      void  TestSingleton ()   {   单例模式:GetInstance()→打印();   }
单例设计模式(懒汉模式,饿汉模式)c++