-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathSingleton.h
98 lines (81 loc) · 1.72 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
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* 单例模板类
*/
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <list>
#include <algorithm>
class SingletonBase
{
class InstanceTable : public std::list < SingletonBase * >
{
public:
InstanceTable()
: is_cleared_(false)
{
};
~InstanceTable()
{
is_cleared_ = true;
for (auto instance : *this)
{
delete instance;
}
}
public:
bool is_cleared_;
};
protected:
SingletonBase()
{
s_instance_table_.push_back(this);
}
virtual ~SingletonBase()
{
if (!s_instance_table_.is_cleared_)
{
InstanceTable::iterator itr = std::find(s_instance_table_.begin(), s_instance_table_.end(), this);
if (itr != s_instance_table_.end())
{
s_instance_table_.erase(itr);
}
}
}
private:
static InstanceTable s_instance_table_;
};
template <typename T>
class Singleton : public SingletonBase
{
public:
static T* getInstance()
{
if (s_singleton_ == nullptr)
{
s_singleton_ = new (std::nothrow) T();
}
return s_singleton_;
}
static void destroy()
{
if (s_singleton_)
{
delete s_singleton_;
}
}
protected:
Singleton() = default;
virtual ~Singleton()
{
s_singleton_ = nullptr;
};
private:
static T* s_singleton_;
};
template<typename T> T* Singleton<T>::s_singleton_ = nullptr;
#define SINGLETON(_class_name_) \
private: \
_class_name_(); \
~_class_name_(); \
friend class Singleton<_class_name_>
#endif