当前位置:网站首页>Common creation and usage of singletons

Common creation and usage of singletons

2022-06-26 13:04:00 Lao Zhao's blog

  1. Purpose : Create a global single instance , Call a class through a single object
  2. establish
  • Definition static Member variables  
  • Constructor privatization
  • Prevent multiple threads from using locks
#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        if (m_Instance == NULL )
        {
            Lock(); // C++ There is no direct Lock operation , Please use the Lock, such as Boost, This is just to illustrate 
            if (m_Instance == NULL )
            {
                m_Instance = new Singleton ();
            }
            UnLock(); // C++ There is no direct Lock operation , Please use the Lock, such as Boost, This is just to illustrate 
        }
        return m_Instance;
    }
 
    static void DestoryInstance()
    {
        if (m_Instance != NULL )
        {
            delete m_Instance;
            m_Instance = NULL ;
        }
    }
 
    int GetTest()
    {
        return m_Test;
    }
 
private:
    Singleton(){ m_Test = 0; }
    static Singleton *m_Instance;
    int m_Test;
};
 
Singleton *Singleton ::m_Instance = NULL;
 
int main(int argc , char *argv [])
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
    Singleton ::DestoryInstance();
 
    return 0;
}
原网站

版权声明
本文为[Lao Zhao's blog]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261211540247.html