#include "stdafx.h" #include <iostream> using namespace std; template <class T> class Singleton { protected: static T m_Singleton; public: Singleton() { } virtual ~Singleton() { } static T& getSingleton() { return m_Singleton; } static T* getSingletonPtr() { return &m_Singleton; } }; class CTest : public Singleton<CTest> { public: CTest() :pName(NULL) { printf("CTest 생성\n"); } virtual ~CTest() { printf("CTest 소멸\n"); if(pName != NULL) { delete pName; pName = NULL; } } void SetName(const char* name, int nSize = 0) { if(pName != NULL) { delete pName; pName = NULL; } int nCharSize = 0; if(nSize > 0) { nCharSize = sizeof(char) * nSize; pName = new char[nCharSize + 1]; } else if(nSize == 0) { while(1) { if(*(name + nCharSize) == '\0') break; ++nCharSize; } pName = new char[nCharSize + 1]; } ++nCharSize; ZeroMemory(pName, nCharSize); CopyMemory(pName, name, nCharSize); } char* GetName() const { return pName; } private: char* pName; }; CTest Singleton<CTest>::m_Singleton; int _tmain(int argc, _TCHAR* argv[]) { for(int i = 0; i < 20; ++i) { char cSingle[25]; char cSinglePtr[30]; sprintf(cSingle, "Singleton Test %02d", i + 1); sprintf(cSinglePtr, "SingletonPtr Test %02d", i + 1); CTest::getSingleton().SetName(cSingle); printf("%s\n", CTest::getSingleton().GetName()); CTest::getSingletonPtr()->SetName(cSinglePtr); printf("%s\n", CTest::getSingletonPtr()->GetName()); } return 0; }