-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleton.h
53 lines (43 loc) · 894 Bytes
/
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
#ifndef SINGLETON_H
#define SINGLETON_H
#include "Debug.h"
#include <cstdlib>
/*
Credit for this class goes to "Game Programming Gems",
section 1.3 by Scott Bilas.
*/
template <class DERIVED>
class Singleton
{
private:
static DERIVED *instance;
public:
Singleton()
{
ASSERT(!instance);
int offset = (size_t)(DERIVED *)1 - (size_t)(Singleton<DERIVED> *)(DERIVED *)1;
instance = (DERIVED *)((size_t)this + offset);
}
virtual ~Singleton()
{
ASSERT(instance);
instance = 0;
}
static DERIVED &getInstance()
{
ASSERT(instance);
return *instance;
}
static DERIVED *getInstancePtr()
{
ASSERT(instance);
return instance;
}
static bool valid()
{
return (instance != 0);
}
};
template <class DERIVED>
DERIVED *Singleton<DERIVED>::instance = 0;
#endif