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

     运行结果如下图:

  • 相关阅读:
    R 多图间距调整
    ggplot2 颜色渐变(离散颜色)设置
    R语言因子排序
    利用plink软件基于LD信息过滤SNP
    利用vcftools比较两个vcf文件
    在R语言中使用Stringr进行字符串操作
    perl 数组快速去除重复元素
    Shell中 ##%% 操作变量名
    Java基础之数值类型之间的转换
    Java中0.2减0.1 结果为什么不是0.1?
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2781575.html
Copyright © 2011-2022 走看看