1 /* ///////////////////////////////////////////////////////////////////////
7 * Brief: Create an instance only before main() begins
10 * Copyright (c) 2008-2020, Waruqi All rights reserved.
11 * //////////////////////////////////////////////////////////////////// */
13 #ifndef EXTL_UTILITY_SINGLETON_H
14 #define EXTL_UTILITY_SINGLETON_H
17 * \brief Create an instance only before main() begins
20 # error singleton.h need be supported by c++.
23 /* ///////////////////////////////////////////////////////////////////////
26 #include "../prefix.h"
27 #include "../synch/synch_traits_selector.h"
28 #include "../synch/scoped_lock.h"
29 /* ///////////////////////////////////////////////////////////////////////
34 /*!\brief singleton class
36 * \param T The object type
38 * \ingroup extl_group_synch
40 template< typename_param_k T
>
44 typedef singleton
<T
> class_type
;
45 typedef T object_type
;
48 static class_type s_self
;
49 static object_type
* s_object
;
52 void do_nothing() const {}
55 /* Ensure the instance() is called before main() begins */
58 object_type
& obj
= class_type::instance();
64 /* Initializes the object and allows multiple initialization */
69 object() = new object_type();
73 /* Uninitializes the object */
83 /* Returns the pointer reference to static object */
84 static object_type
*& object()
86 #ifdef EXTL_COMPILER_IS_DMC
87 static object_type
* p
= NULL
;
89 #else /* DMC: Link error */
95 /* Returns a reference of the object */
96 static object_type
& instance()
98 /* Initializes the object and allows multiple initialization */
101 /* Force the instantiation of singleton<T>,
102 * whose constructor is called before main() begins
106 EXTL_MESSAGE_ASSERT(NULL
!= object(), "The singleton is not existed!");
110 template < typename_param_k T
>
111 typename_type_k singleton
<T
>::object_type
* singleton
<T
>::s_object
= NULL
;
113 template < typename_param_k T
>
114 singleton
<T
> singleton
<T
>::s_self
;
116 /* ///////////////////////////////////////////////////////////////////////
121 /* //////////////////////////////////////////////////////////////////// */
122 #endif /* EXTL_UTILITY_SINGLETON_H */
123 /* //////////////////////////////////////////////////////////////////// */