static.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #if !defined(INCLUDED_GENERIC_STATIC_H)
00023 #define INCLUDED_GENERIC_STATIC_H
00024
00027
00028 #include <cstddef>
00029
00030 class Null {
00031 };
00032
00040 template < typename Type, typename Context = Null >
00041 class Static {
00042 static Type m_instance;
00043 public:
00044 static Type& instance() {
00045 return m_instance;
00046 }
00047 };
00048
00049 template<typename Type, typename Context>
00050 Type Static<Type, Context>::m_instance;
00051
00052
00061 template < typename Type, typename Context = Null >
00062 class LazyStatic {
00063 static Type* m_instance;
00064 public:
00065 static Type& instance() {
00066 if (m_instance == 0) {
00067 m_instance = new Type;
00068 }
00069 return *m_instance;
00070 }
00071 };
00072
00073 template<typename Type, typename Context>
00074 Type* LazyStatic<Type, Context>::m_instance;
00075
00076
00084 template < typename Type, typename Context = Null >
00085 class CountedStatic {
00086 static std::size_t m_refcount;
00087 static Type* m_instance;
00088 public:
00089 static Type& instance() {
00090 return *m_instance;
00091 }
00092 static void capture() {
00093 if (++m_refcount == 1) {
00094 m_instance = new Type;
00095 }
00096 }
00097 static void release() {
00098 if (--m_refcount == 0) {
00099 delete m_instance;
00100 }
00101 }
00102 };
00103
00104 template<typename Type, typename Context>
00105 std::size_t CountedStatic<Type, Context>::m_refcount;
00106 template<typename Type, typename Context>
00107 Type* CountedStatic<Type, Context>::m_instance;
00108
00117 template < typename Type, typename Context = Null >
00118 class SmartStatic {
00119 public:
00120 SmartStatic() {
00121 CountedStatic<Type, Context>::capture();
00122 }
00123 ~SmartStatic() {
00124 CountedStatic<Type, Context>::release();
00125 }
00126 Type& instance() {
00127 return CountedStatic<Type, Context>::instance();
00128 }
00129 };
00130
00131
00132 #endif