-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.h
51 lines (41 loc) · 826 Bytes
/
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
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <mutex>
#include <memory>
namespace zy{
template<typename T>
class Singleton
{
public:
struct Initializer
{
Initializer() {
Singleton<T>::get_once_flag();
Singleton<T>::get_instance();
}
void do_nothing() const {}
};
static Initializer I;
public:
static std::shared_ptr<T> instance()
{
I.do_nothing();
std::call_once(get_once_flag(), []{get_instance().reset(new T); });
return get_instance();
}
private:
static std::once_flag& get_once_flag()
{
static std::once_flag once_flag;
return once_flag;
}
static std::shared_ptr<T>& get_instance()
{
static std::shared_ptr<T> instance_;
return instance_;
}
};
template<typename T>
typename Singleton<T>::Initializer Singleton<T>::I;
} /*namespace zy*/
#endif /*__SINGLETON_H__*/