当前位置:网站首页>单例的常用创建和使用方式

单例的常用创建和使用方式

2022-06-26 12:37:00 老赵的博客

  1. 目的:创建一个全局的单一实例,通过单一对象来调用类
  2. 创建
  • 定义static 成员变量 
  • 构造函数私有化
  • 防止多线程使用锁
#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        if (m_Instance == NULL )
        {
            Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
            if (m_Instance == NULL )
            {
                m_Instance = new Singleton ();
            }
            UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
        }
        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;
}
原网站

版权声明
本文为[老赵的博客]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sinat_20962951/article/details/125387507