zoukankan      html  css  js  c++  java
  • 不考虑线程安全的初级单例C++代码

    本文实现的是不考虑线程安全的初级单例Singleton的C++代码,目的是为了学习单例,考虑线程安全的代码放在后面的blog里。

    #include <iostream>
    using namespace std;
    
    class Singleton{
    public:
        static Singleton* GetInstance()                // 得到单例
        {
            if (m_Instance == NULL)
            {
                m_Instance = new Singleton();
                cout<<"m_Instance created!"<<endl;
            }
            else
            {
                cout<<"m_Instance already exist!"<<endl;
            }
            return m_Instance;
        }
    
        static void DeleteInstance()                // 删除单例
        {
            if (m_Instance)
            {
                delete m_Instance;
                m_Instance = NULL;//指针记得置NULL
                cout<<"m_Instance deleted!"<<endl<<endl;
            }
            else
            {
                cout<<"m_Instance already deleted!"<<endl;
            }
        }
    
        void TestPrint()//一个小的测试函数
        {
            cout<<"lala"<<endl;
        }
    private:
        static Singleton* m_Instance;                // 实现单例就靠它了
    
        Singleton(){}                                // 构造函数要封为private
        ~Singleton(){}                                // 同样析构函数也是
    };
    
    Singleton* Singleton::m_Instance = NULL;        // 静态变量的初始化要放在类外,而且也要放在构造函数外
    
    int main()
    {
        Singleton* psg = Singleton::GetInstance();    // 第一次调用GetInstance(),会创建一个对象
        Singleton* psg2 = Singleton::GetInstance();    // 第二次调用GetInstance(),就不会创建对象了
        psg->TestPrint();                            // 测试一下这个对象好不好用
        Singleton::DeleteInstance();                // 将其删除掉
        Singleton::GetInstance()->TestPrint();        // 再用GetInstance()返回的指针再测试一下好不好用,同时检验是否再次创建了对象
        return 1;
    }

     运行结果如下图:

  • 相关阅读:
    【SCOI2012】滑雪
    【NOI2008】假面舞会
    ※初赛知识总结※
    【FJSC2012】足球
    【中山市选2011】杀人游戏
    【SDOI2008】洞穴勘测
    【SNOI2017】炸弹
    【LGOJ1606】白银莲花池
    int类型中为什么负数比正数多了一个数?
    utf8、utf16、utf32之间的格式
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2781575.html
Copyright © 2011-2022 走看看