version 0.1.3
[fms.git] / include / pthreadwrapper / singleton.h
diff --git a/include/pthreadwrapper/singleton.h b/include/pthreadwrapper/singleton.h
new file mode 100644 (file)
index 0000000..bfe99ad
--- /dev/null
@@ -0,0 +1,69 @@
+#ifndef _pthread_singleton_\r
+#define _pthread_singleton_\r
+\r
+#include "noncopyable.h"\r
+#include "guard.h"\r
+\r
+#include <cassert>\r
+\r
+namespace PThread\r
+{\r
+\r
+//! SingletonDestroyer\r
+template <class T>\r
+class Destroyer {\r
+  \r
+  T* doomed;\r
+  \r
+ public:\r
+  \r
+  Destroyer(T* q) : doomed(q) {\r
+    assert(doomed);\r
+  }\r
+  \r
+  ~Destroyer();\r
+\r
+};\r
+\r
+template <class T>\r
+Destroyer<T>::~Destroyer() {\r
+  \r
+  try {\r
+    \r
+    if(doomed)\r
+      delete doomed;\r
+    \r
+  } catch(...) { }\r
+  \r
+  doomed = 0;\r
+  \r
+}   \r
+\r
+template <class T>\r
+class Singleton:public NonCopyable\r
+{\r
+public:\r
+\r
+       static T *Instance();\r
+\r
+private:\r
+       \r
+};\r
+\r
+template <class T>\r
+T *Singleton<T>::Instance()\r
+{\r
+       static T *obj=0;\r
+       static Mutex mutex;\r
+       Guard g(mutex);\r
+       if(obj==0)\r
+       {\r
+               obj=new T();\r
+               static Destroyer<T> des(obj);\r
+       }\r
+       return const_cast<T*>(obj);\r
+}\r
+\r
+}      // namespace\r
+\r
+#endif // _pthread_singleton_\r