Programming/Win32 API
09. 템플릿 싱글톤 패턴
KingSSSSS
2017. 12. 20. 10:15
#include <stdlib.h>
int atexit(void (*func)(void));
atexit()는 성공시 0, 오류시 0이 아닌 값을 반환합니다.
인자로 전달된 포인터함수가 프로그램 종료 시 자동으로 호출되어야 할 함수는 32개 까지 등록할수있다
등록된 순서의 역순으로 호출 된다 프로그램이 정상적으로 호출 됄때에만 호출 된다
// 싱글톤
template <typename T>
class JSingleton
{
protected:
JSingleton() {}
virtual ~JSingleton () {}
JSingleton(const JSingleton& s) {}
private:
static T * mSingleton;
static void destroy()
{
delete mSingleton ;
}
public:
static T * GetInstance()
{
if (mSingleton == NULL)
{
mSingleton = new T();
// 싱글톤객체는메모리관리가어려워 atexit() 함수를쓴다
atexit(destroy ); // 프로그램이정상적으로종료된다면종료직전에호출된다
}
return mSingleton ;
};
};
// JSingleton 의static T* mSingleton 의초기화
template <typename T>
T* JSingleton <T>:: mSingleton = NULL ;
// 싱클톤상속받는다
class Test : public JSingleton<Test >
{
public:
int i ;
};
INT WINAPI wWinMain( HINSTANCE hInstance , HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
// 싱글톤객체사용법
Test* test1 = Test:: GetInstance();
test1->i = 9;
Test* test2 = Test:: GetInstance();
test2->i = 90;
return 0 ;
}