-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.h
More file actions
91 lines (70 loc) · 2.15 KB
/
singleton.h
File metadata and controls
91 lines (70 loc) · 2.15 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
90
91
/*
Default thread safe singleton
Example of using:
class Logger
{
friend ext::Singleton<Logger>;
public:
LoggerData() = default;
~LoggerData() = default;
};
*/
#pragma once
#include <atomic>
#include <ext/error/dump_writer.h>
#include <ext/types/utils.h>
namespace ext {
// Flag that shows created singletons
template<class T>
std::atomic_bool kSingletonCreated = false;
// Flag that shows destroyed singletons
template<class T>
std::atomic_bool kSingletonDestroyed = false;
template<class T>
struct Singleton final
{
static T& Instance()
{
/*
Check the situations like this:
struct MainSingleton
{
MainSingleton() { get_singleton<OtherSingleton>(); }
~MainSingleton() { get_singleton<OtherSingleton>(); }
};
During destroying services OtherSingleton will be destroyed first and when we try to get it in the
MainSingleton destructor we might create an inconsistency.
*/
if (kSingletonDestroyed<T>)
{
std::cerr << "Trying to get already destroyed service " << ext::type_name<T>()
<< ". Check service declaration order." << std::endl;
if (IsDebuggerPresent())
DebugBreak();
}
// according to the standard, this code is lazy and thread safe
static SingletonWatcher watcher;
return watcher.object;
}
Singleton() = delete; // no constructor
~Singleton() = delete; // no destructor
// prohibit copying
Singleton(Singleton const&) = delete;
Singleton& operator= (Singleton const&) = delete;
private:
// Help class which will help to detect objects creation after it destroying
struct SingletonWatcher
{
SingletonWatcher() { kSingletonCreated<T> = true; }
~SingletonWatcher() { kSingletonDestroyed<T> = true; }
SingletonWatcher(SingletonWatcher const&) = delete;
SingletonWatcher& operator= (SingletonWatcher const&) = delete;
T object;
};
};
template<class T>
[[nodiscard]] static T& get_singleton()
{
return Singleton<T>::Instance();
}
} // namespace ext