lean cpp library
A lean C++ library providing efficient utility classes for high-performance C++ applications.
|
00001 /*****************************************************/ 00002 /* lean Smart (c) Tobias Zirr 2011 */ 00003 /*****************************************************/ 00004 00005 #ifndef LEAN_SMART_HANDLE_GUARD 00006 #define LEAN_SMART_HANDLE_GUARD 00007 00008 #include "../lean.h" 00009 #include "../tags/noncopyable.h" 00010 00011 namespace lean 00012 { 00013 namespace smart 00014 { 00015 00017 template <class Handle> 00018 struct close_handle_policy 00019 { 00021 static LEAN_INLINE Handle invalid() 00022 { 00023 return INVALID_HANDLE_VALUE; 00024 } 00026 static LEAN_INLINE void release(Handle handle) 00027 { 00028 if (handle != NULL && handle != INVALID_HANDLE_VALUE) 00029 ::CloseHandle(handle); 00030 } 00031 }; 00032 00034 template <class Handle> 00035 struct destroy_window_policy 00036 { 00038 static LEAN_INLINE Handle invalid() 00039 { 00040 return NULL; 00041 } 00043 static LEAN_INLINE void release(Handle handle) 00044 { 00045 if (handle != NULL) 00046 ::DestroyWindow(handle); 00047 } 00048 }; 00049 00051 template <class Handle> 00052 struct free_library_policy 00053 { 00055 static LEAN_INLINE Handle invalid() 00056 { 00057 return NULL; 00058 } 00060 static LEAN_INLINE void release(Handle handle) 00061 { 00062 if (handle != NULL) 00063 ::FreeLibrary(handle); 00064 } 00065 }; 00066 00068 template < class Handle, class ReleasePolicy = close_handle_policy<Handle> > 00069 class handle_guard : public noncopyable 00070 { 00071 private: 00072 Handle m_handle; 00073 00074 public: 00076 LEAN_INLINE explicit handle_guard(Handle handle) 00077 : m_handle(handle) { } 00079 LEAN_INLINE ~handle_guard() 00080 { 00081 ReleasePolicy::release(m_handle); 00082 } 00083 00085 LEAN_INLINE Handle detatch() 00086 { 00087 Handle handle = m_handle; 00088 m_handle = ReleasePolicy::invalid(); 00089 return handle; 00090 } 00091 00093 LEAN_INLINE Handle get() const { return m_handle; } 00095 LEAN_INLINE operator Handle() const { return get(); } 00096 }; 00097 00098 } // namespace 00099 00100 using smart::handle_guard; 00101 00102 } // namespace 00103 00104 #endif