forked from somma/_MyLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Singleton.h
85 lines (70 loc) · 2.63 KB
/
Singleton.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**----------------------------------------------------------------------------
* Singleton.h
*-----------------------------------------------------------------------------
*
*-----------------------------------------------------------------------------
* All rights reserved by Noh,Yonghwan (fixbrain@gmail.com, unsorted@msn.com)
*-----------------------------------------------------------------------------
* 26:8:2011 15:34 created
**---------------------------------------------------------------------------*/
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#ifdef _M_AMD64
#define MyRefCount LONGLONG
#define MyInterlockedIncrement InterlockedIncrement64
#define MyInterlockedDecrement InterlockedDecrement64
#define MyInterlockedCompareExchange InterlockedCompareExchange64
#define MyInterlockedCompareExchange InterlockedCompareExchange64
#define MyInterlockedAnd _InterlockedAnd64
#elif defined (_M_IX86)
#define MyRefCount LONG
#define MyInterlockedIncrement InterlockedIncrement
#define MyInterlockedDecrement InterlockedDecrement
#define MyInterlockedCompareExchange InterlockedCompareExchange
#define MyInterlockedCompareExchange InterlockedCompareExchange
#define MyInterlockedAnd _InterlockedAnd
#else
#error !!! Need to write code for this architecture?
#endif
template <typename T>
class Singleton
{
private:
static MyRefCount mRefCount;
static T* mInstance;
Singleton(){ }
~Singleton(){}
static void IncrementReferenceCount()
{
_ASSERTE(NULL != mInstance);
MyInterlockedIncrement(&mRefCount);
}
static void DecrementReferenceCount()
{
_ASSERTE(0 != mRefCount); if (0 == mRefCount) return;
MyInterlockedDecrement(&mRefCount);
if (0 == MyInterlockedCompareExchange(&mRefCount, 0, 0))
{
delete mInstance; mInstance = NULL;
}
}
public:
static T* GetInstancePointer()
{
if (NULL == mInstance) {mInstance = new T();}
Singleton::IncrementReferenceCount();
return mInstance;
}
static void ReleaseInstance()
{
Singleton::DecrementReferenceCount();
}
#ifdef ALTONG_TEST_EXPORTS
// debug / test ¿ë ¸Þ¼Òµå
static MyRefCount GetRefCount(){return mRefCount;}
static T* GetInstanceForTest(){return mInstance;}
#endif//ALTONG_TEST_EXPORTS
};
template <typename T> T* Singleton<T>::mInstance = NULL;
template <typename T> MyRefCount Singleton<T>::mRefCount = 0;