C++单例模式call_once

#include <iostream>
#include <mutex>
using namespace std;

class MyInstance
{
   MyInstance(){}

public:
   static MyInstance *getInstance()
   {
      std::call_once(m_flag, [&](){
         m_instance = new MyInstance();
         cout << "createInstance " << 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;
   static std::once_flag m_flag;
};

MyInstance *MyInstance::m_instance = NULL;
std::once_flag MyInstance::m_flag;

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;
}
$ g++ call_once.cpp -std=c++11 -pthread
$ ./a.out 
createInstance 0x133cc20
m_instance1 0x133cc20
m_instance2 0x133cc20
~Release
posted @ 2022-08-07 15:46  thomas_blog  阅读(164)  评论(0编辑  收藏  举报