-
Notifications
You must be signed in to change notification settings - Fork 2
/
singleton.hpp
89 lines (68 loc) · 1.76 KB
/
singleton.hpp
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
#ifndef SINGLETON_HPP
#define SINGLETON_HPP
#include <utils/object.hpp>
#include <iostream>
#include <memory>
#include <mutex>
namespace Lazy {
class Singleton
{
Singleton() { std::cout << "Lazy Singleton" << std::endl; }
~Singleton() { std::cout << "Lazy ~Singleton" << std::endl; }
DISABLE_COPY_MOVE(Singleton)
public:
static Singleton &instance()
{
static Singleton s; // C++11 thread safe
return s;
}
};
} // namespace Lazy
namespace Hungry {
class Singleton
{
Singleton() { std::cout << "Hungry Singleton" << std::endl; }
//~Singleton() { std::cout << "Hungry ~Singleton" << std::endl; }
DISABLE_COPY_MOVE(Singleton)
static std::unique_ptr<Singleton> s_singleton_ptr;
static std::mutex s_mutex;
public:
~Singleton() { std::cout << "Hungry ~Singleton" << std::endl; }
// ① This the first way to implement Singleton
// static Singleton &instance()
// {
// std::unique_lock locker(s_mutex);
// if (!s_singleton_ptr) {
// s_singleton_ptr.reset(new Singleton);
// }
// return *s_singleton_ptr;
// }
// ② This the second way to implement Singleton
static Singleton &instance()
{
static std::once_flag flag;
std::call_once(flag, []() {
if (!s_singleton_ptr) {
s_singleton_ptr.reset(new Singleton);
}
});
return *s_singleton_ptr;
}
};
} // namespace Hungry
namespace LazyTemplate {
template<typename T>
class Singleton
{
Singleton() = delete;
~Singleton() = delete;
DISABLE_COPY_MOVE(Singleton)
public:
static T &instance()
{
static T t; // C++11 thread safe
return t;
}
};
} // namespace LazyTemplate
#endif // SINGLETON_HPP