내가만든게아니라 어디 예제로 나온건데
싱글톤 처음보는거라... 방금검색하고 다시읽어봄
#include <iostream>
using namespace std;
template <typename T>
class MySingleton
{
public:
MySingleton() {}
virtual ~MySingleton() {}
// 이 멤버를 통해서만 생성이 가능하다.
static T* GetSingleton()
{
// 아직 생성이 되어 있지 않으면 생성한다.
if (NULL == _Singleton) {
_Singleton = new T;
}
return (_Singleton);
}
static void Release()
{
delete _Singleton;
_Singleton = NULL;
}
private:
static T* _Singleton;
};
template <typename T> T* MySingleton<T> ::_Singleton = NULL;
// 싱글톤 클래스 템플릿을 상속 받으면서 파라미터에 본 클래스를 넘긴다.
class MyObject : public MySingleton<MyObject>
{
public:
MyObject() : _nValue(10) {}
void SetValue(int Value) { _nValue = Value; }
int GetValue() { return _nValue; }
private:
int _nValue;
};
void main()
{
MyObject* MyObj1 = MyObject::GetSingleton();
cout << MyObj1->GetValue() << endl;
// MyObj2는 Myobj1과 동일한 객체이다.
MyObject* MyObj2 = MyObject::GetSingleton();
MyObj2->SetValue(20);
cout << MyObj1->GetValue() << endl;
cout << MyObj2->GetValue() << endl;
}
=============================================
메인함수 따라가면
1. MyObject* MyObj1 = MyObject::GetSingleton();
rvalue인 (MyObject::GetSingleton();)부터 말하면
T는 MyObject이고MySingleton 클래스의 GetSingleton();을 한다.
NULL == _Singleton 이므로 (아직생성이 안되있으므로)
_Singleton = new T; 를하고 T를반환함.
여기서 T는 MyObject 클래스 인것임.
그러니까
MyObject* MyObj1 = new MyObject; 인거고
MyObject() : _nValue(10) {}
디폴트 생성자에 의해 public에 있는 _nValue(10)으로
private: int _nValue; 의 값이 10이됨
//-------------------------------------------------------------
2. cout << MyObj1->GetValue() << endl;
Myobj1의 _nValue값 (10)을 출력함
//-------------------------------------------------------------
3. MyObject* MyObj2 = MyObject::GetSingleton();
1.과 같은이유로
rvalue인 (MyObject::GetSingleton();)부터 말하면
T는 MyObject이고MySingleton 클래스의 GetSingleton();을 한다.
그런데
if (NULL == _Singleton)
{
_Singleton = new T;
}
1번과정에서 _Singleton = new MyObj 이었으므로 NULL아니고
그다음문장인 return 을거쳐서 1번에서 만든 MyObj를 반환함
MyObject* MyObj2 = MyObj;
결국
MyObject* MyObj1 = MyObject* MyObj2 = MyObj;
다같은거니 private: _nValue 값또한 전부 10이고
//------------------------------------------------------------------
4. MyObj2->SetValue(20);
private: _nValue 값 20으로바꾸고
5~6
cout << MyObj1->GetValue() << endl;
cout << MyObj2->GetValue() << endl;
둘다 바뀐 20값 출력함
맞음?
댓글 0