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;
    }

     运行结果如下图:

  • 相关阅读:
    CPU Cache与缓存行
    linux 查看命令总结
    idea自个常用工具的总结
    《人月神话》
    啊哈,翻转
    Scrapy爬虫之豆瓣TOP250
    87的100次幂除以7的余数是多少
    python之sqlite3 用法详解
    Sublime Text 3 插件SublimeLinter/PEP8安装&配置,检查代码规范
    urlparse之urljoin() 爬虫必备
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2781575.html
Copyright © 2011-2022 走看看