common_util
Loading...
Searching...
No Matches
singleton.h
Go to the documentation of this file.
1
19#pragma once
20
21#include <mutex>
22
27#undef CUTL_COPY_AND_ASSIGN
28#define CUTL_COPY_AND_ASSIGN(classname) \
29 classname(const classname &) = delete; \
30 classname &operator=(const classname &) = delete;
31
36#undef CUTL_SINGLETON_PTR
37#define CUTL_SINGLETON_PTR(classname) \
38public: \
39 static classname *get_instance(bool create_if_needed = true) \
40 { \
41 static classname *obj = nullptr; \
42 if (!obj && create_if_needed) \
43 { \
44 static std::once_flag flag; \
45 std::call_once(flag, [&] { obj = new (std::nothrow) classname(); }); \
46 } \
47 return obj; \
48 } \
49 ~classname(); \
50 \
51private: \
52 classname(); \
53 CUTL_COPY_AND_ASSIGN(classname)
54
59#undef CUTL_SINGLETON_PTR_DEFAULT_CTOR
60#define CUTL_SINGLETON_PTR_DEFAULT_CTOR(classname) \
61public: \
62 static classname *get_instance(bool create_if_needed = true) \
63 { \
64 static classname *obj = nullptr; \
65 if (!obj && create_if_needed) \
66 { \
67 static std::once_flag flag; \
68 std::call_once(flag, [&] { obj = new (std::nothrow) classname(); }); \
69 } \
70 return obj; \
71 } \
72 ~classname(); \
73 \
74private: \
75 classname() = default; \
76 CUTL_COPY_AND_ASSIGN(classname)
77
82#undef CUTL_SINGLETON_REF
83#define CUTL_SINGLETON_REF(classname) \
84public: \
85 static classname &get_instance(bool create_if_needed = true) \
86 { \
87 static classname obj; \
88 return obj; \
89 } \
90 ~classname(); \
91 \
92private: \
93 classname(); \
94 CUTL_COPY_AND_ASSIGN(classname)
95
100#undef CUTL_SINGLETON_REF_DEFAULT_CTOR
101#define CUTL_SINGLETON_REF_DEFAULT_CTOR(classname) \
102public: \
103 static classname &get_instance(bool create_if_needed = true) \
104 { \
105 static classname obj; \
106 return obj; \
107 } \
108 ~classname(); \
109 \
110private: \
111 classname() = default; \
112 CUTL_COPY_AND_ASSIGN(classname)