-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.h
More file actions
89 lines (74 loc) · 2.08 KB
/
Copy pathSingleton.h
File metadata and controls
89 lines (74 loc) · 2.08 KB
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
86
87
88
89
// Copyright 2006-13 HumaNature Studios Inc.
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
namespace core {
// for tracking all singletons at run-time
class SingletonBase
{
public:
static std::map<std::string, SingletonBase*>* sSingletonMap;
};
template<typename SingletonType>
class Singleton
: public SingletonBase
{
protected:
static SingletonType* sInstance;
public:
// Returns a reference to singleton object
static SingletonType& Instance()
{
return *sInstance;
}
// Returns a pointer to singleton object
static SingletonType* InstancePtr()
{
return sInstance;
}
Singleton()
{
// add to global list
(*SingletonBase::sSingletonMap)[GetTypeName<SingletonType>()] = this;
}
virtual ~Singleton()
{
if (sInstance == this)
{
// remove from global list
auto it = SingletonBase::sSingletonMap->find(GetTypeName<SingletonType>());
SingletonBase::sSingletonMap->erase(it);
sInstance = nullptr;
}
}
// explicitly create
static SingletonType& Create()
{
if(sInstance == nullptr)
{
sInstance = new SingletonType;
}
return *sInstance;
}
// explicitly destroy
static void Destroy()
{
if (sInstance)
{
delete sInstance;
sInstance = nullptr;
}
}
// use to override a singleton with a new one
// note- does not dispose of old one
static void Override(SingletonType* inst)
{
sInstance = inst;
}
private:
// Prevent copy-construction
Singleton(const Singleton&);
// Prevent assignment
Singleton& operator=(const Singleton&);
};
} // namespace core
#endif // __SINGLETON_H__