#include <iostream>
using namespace std;
// 单例模式 --- 懒汉式
class Singleton
{
private:
Singleton()
{
}
public:
static Singleton* GetInstance()
{
if (m_instance == nullptr)
m_instance = new Singleton;
handle_count++;
return m_instance;
}
static void Release()
{
if (handle_count > 0)
handle_count--;
if (m_instance != nullptr && handle_count == 0)
{
delete m_instance;
m_instance = nullptr;
}
}
private:
static int handle_count; // 引用计数
static Singleton* m_instance;
};
Singleton* Singleton::m_instance = nullptr;
int Singleton::handle_count = 0;
int main()
{
// Singleton s1;
// Singleton s2;
Singleton* ps = Singleton::GetInstance();
Singleton* ps1 = Singleton::GetInstance();
Singleton* ps2 = Singleton::GetInstance();
Singleton* ps3 = Singleton::GetInstance();
cout << ps << endl;
cout << ps1 << endl;
cout << ps2 << endl;
cout << ps3 << endl;
Singleton::Release();
Singleton::Release();
return 0;
}