#include "stdafx.h" #include <iostream> using namespace std; class Singleton { private: static Singleton *m_instance; Singleton() { cout << "Singleton Construct" << endl; } ~Singleton() { if (m_instance) { delete m_instance; } cout << "Singleton Destruct" << endl; } public: static Singleton* GetInstance() { if (!m_instance) { m_instance = new Singleton; } return m_instance; } }; Singleton* Singleton::m_instance = NULL; int main() { //Singleton *pSingletonA = new Singleton; //编译会报错,因为不能访问私有函数 Singleton *pSingletonA = Singleton::GetInstance(); Singleton *pSingletonB = Singleton::GetInstance(); if (pSingletonA == pSingletonB) cout << "Same Instance" << endl; return 0; }
时间: 2024-10-07 14:24:53