-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton_template.cpp
More file actions
61 lines (49 loc) · 1.29 KB
/
singleton_template.cpp
File metadata and controls
61 lines (49 loc) · 1.29 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
#include <iostream>
#include <memory>
using namespace std;
template<typename T>
class Singleton {
public:
static T& get() {
std::once_flag flag;
std::call_once(flag, [&]() {
_instance = std::unique_ptr<T>(new T());
_instance->init();
});
return *_instance;
}
static void destroy() {
static std::once_flag flag;
std::call_once(flag, [&]() { _instance.reset(nullptr); });
}
private:
static std::unique_ptr<T> _instance;
};
template<typename T>
std::unique_ptr<T> Singleton<T>::_instance = nullptr;
class Instance {
public:
void func() {
std::cout << "do something" << std::endl;
}
friend class default_delete<Instance>;
friend class Singleton<Instance>;
// 如果内部需要使用以下某个函数,将其设置为 private default
Instance(const Instance&) = delete;
Instance(Instance&&) = delete;
Instance& operator=(const Instance&) = delete;
Instance& operator=(const Instance&&) = delete;
private:
Instance() {
// load messages from config and init single instance
}
void init() {
}
~Instance() = default;
};
int main() {
Instance& ins = Singleton<Instance>::get();
ins.func();
Singleton<Instance>::destroy();
return 0;
}