C++单例模式

#include <iostream>
using namespace std;

class MyInstance
{
   MyInstance(){}

public:
   static MyInstance *getInstance()
   {
      if(m_instance == NULL)
      {
         m_instance = new MyInstance();
         cout << "getInstance " << m_instance << endl;
         static Release r;
      }

      return m_instance;
   }

   /* 用于释放对象 */
   class Release
   {
   public:
      ~Release()
      {
         if(MyInstance::m_instance != NULL)
         {
            cout << "~Release" << endl;
            delete MyInstance::m_instance;
            MyInstance::m_instance = NULL;
         }
      }
   };

private:
   static MyInstance *m_instance;
};

MyInstance *MyInstance::m_instance = NULL;

int main()
{
   MyInstance *m_instance1 = MyInstance::getInstance();
   cout << "m_instance1 " << m_instance1 << endl;

   MyInstance *m_instance2 = MyInstance::getInstance();
   cout << "m_instance2 " << m_instance2 << endl;

   return 0;
}
$ ./a.out         
getInstance 0x121fc20
m_instance1 0x121fc20
m_instance2 0x121fc20
~Release
posted @ 2022-08-07 15:11  thomas_blog  阅读(18)  评论(0编辑  收藏  举报