【C++ 单例模式】

发布时间:2023年12月30日

正确的析构 静态实例和回收类
SingletonMode.cpp

#include <iostream>

class Singleton
{
  private:
    Singleton(){
        std::cout << "构造" << std::endl;
    };
    ~Singleton()
    {
        std::cout << "析构" << std::endl;
    }

  public:
    static Singleton *getInstance()
    {
        static Singleton local_instance;
        return &local_instance;
    }

};


class SingletonPattern
{

private:
	SingletonPattern()
    {
        std::cout << "创建单例模式对象!\n";
    }
	~SingletonPattern()
    {

    }
private:
	static SingletonPattern* m_Instance;

public:
	static SingletonPattern* GetInstance()
    {
        if (m_Instance == nullptr) 
        {
            m_Instance = new SingletonPattern();
        }
        std::cout << "返回单例模式句柄!\n";
        return m_Instance;
    }

	void display()
    {
        std::cout << "使用单例模式!\n" ;
    }
private:
	class CGabor
	{
	public:
		~CGabor(){
			if (SingletonPattern::m_Instance){
				delete SingletonPattern::m_Instance;
				SingletonPattern::m_Instance = NULL;
                std::cout << "SingletonPattern 析构" << std::endl;
			}
		}
	};
	static CGabor m_Gabor;
};

SingletonPattern* SingletonPattern:: m_Instance = nullptr;
SingletonPattern::CGabor SingletonPattern::m_Gabor;

// g++ SingletonMode.cpp -o SingletonMode -std=c++11
int main()
{
    Singleton *a = Singleton::getInstance();
    Singleton *b = Singleton::getInstance();
    if(a==b){
        std::cout<< "a==b" <<'\n';
    }
    SingletonPattern* m_Test = SingletonPattern::GetInstance();
	m_Test->display();
    return 0;
}
文章来源:https://blog.csdn.net/weixin_45397344/article/details/135283275
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。