【C++ 单例模式】

正确的析构 静态实例和回收类
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;
}

你可能感兴趣的:(c++,单例模式,开发语言)