LBIBCell
 All Classes Functions Variables Friends Pages
Singleton.hpp
1 /* Copyright (c) 2013 David Sichau <mail"at"sichau"dot"eu>
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to deal
5  * in the Software without restriction, including without limitation the rights
6  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7  * copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
18  * THE SOFTWARE.
19  *
20  */
21 
22 #ifndef UTILIB_SINGLETON_HPP_
23 #define UTILIB_SINGLETON_HPP_
24 
25 
26 #include <UtilLib/include/Exception.hpp>
27 namespace UtilLib {
37 template <class T>
38 class Singleton {
39  public:
40  // disallow creation, copying and assignment
41 
45  Singleton() = delete;
46 
51  Singleton(const Singleton& S) = delete;
52 
57  Singleton& operator=(const Singleton& S) = delete;
58 
62  static T& instance();
63 
66  ~Singleton();
67 
68  private:
72  static void create();
73 
76  static T* pInstance_;
77 
80  static bool destroyed_;
81 };
82 
89 template <class T>
91  if (!pInstance_) {
92  if (destroyed_) {
93  // dead reference
94  throw Exception("The instance was already destroyed");
95  } else {
96  // initial creation
97  create();
98  }
99  }
100  return *pInstance_;
101 }
102 
103 template <class T> Singleton<T>::~Singleton() {
104  pInstance_ = 0;
105  destroyed_ = true;
106 }
107 
108 template <class T>
109 void Singleton<T>::create() {
110  static T theInstance;
111  pInstance_ = &theInstance;
112 }
113 
114 template <class T>
115 T * Singleton<T>::pInstance_ = 0;
116 template <class T>
117 bool Singleton<T>::destroyed_ = false;
118 }
119 
120 #endif /* UTILIB_SINGLETON_HPP_ */
static T & instance()
Definition: Singleton.hpp:90
Singleton & operator=(const Singleton &S)=delete