1 /* 2 * Copyright 2001-2007, Ingo Weinhold, bonefish@users.sf.net. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef _AUTO_DELETER_H 6 #define _AUTO_DELETER_H 7 8 /*! Scope-based automatic deletion of objects/arrays. 9 ObjectDeleter - deletes an object 10 ArrayDeleter - deletes an array 11 MemoryDeleter - free()s malloc()ed memory 12 */ 13 14 #include <stdlib.h> 15 16 namespace BPrivate { 17 18 // AutoDeleter 19 20 template<typename C, typename DeleteFunc> 21 class AutoDeleter { 22 public: 23 inline AutoDeleter() 24 : fObject(NULL) 25 { 26 } 27 28 inline AutoDeleter(C *object) 29 : fObject(object) 30 { 31 } 32 33 inline ~AutoDeleter() 34 { 35 fDelete(fObject); 36 } 37 38 inline void SetTo(C *object) 39 { 40 if (object != fObject) { 41 fDelete(fObject); 42 fObject = object; 43 } 44 } 45 46 inline void Unset() 47 { 48 SetTo(NULL); 49 } 50 51 inline void Delete() 52 { 53 SetTo(NULL); 54 } 55 56 inline C *Get() const 57 { 58 return fObject; 59 } 60 61 inline C *Detach() 62 { 63 C *object = fObject; 64 fObject = NULL; 65 return object; 66 } 67 68 private: 69 C *fObject; 70 DeleteFunc fDelete; 71 }; 72 73 74 // ObjectDeleter 75 76 template<typename C> 77 struct ObjectDelete 78 { 79 inline void operator()(C *object) 80 { 81 delete object; 82 } 83 }; 84 85 template<typename C> 86 struct ObjectDeleter : AutoDeleter<C, ObjectDelete<C> > 87 { 88 ObjectDeleter() : AutoDeleter<C, ObjectDelete<C> >() {} 89 ObjectDeleter(C *object) : AutoDeleter<C, ObjectDelete<C> >(object) {} 90 }; 91 92 93 // ArrayDeleter 94 95 template<typename C> 96 struct ArrayDelete 97 { 98 inline void operator()(C *array) 99 { 100 delete[] array; 101 } 102 }; 103 104 template<typename C> 105 struct ArrayDeleter : AutoDeleter<C, ArrayDelete<C> > 106 { 107 ArrayDeleter() : AutoDeleter<C, ArrayDelete<C> >() {} 108 ArrayDeleter(C *array) : AutoDeleter<C, ArrayDelete<C> >(array) {} 109 }; 110 111 112 // MemoryDeleter 113 114 struct MemoryDelete 115 { 116 inline void operator()(void *memory) 117 { 118 free(memory); 119 } 120 }; 121 122 struct MemoryDeleter : AutoDeleter<void, MemoryDelete > 123 { 124 MemoryDeleter() : AutoDeleter<void, MemoryDelete >() {} 125 MemoryDeleter(void *memory) : AutoDeleter<void, MemoryDelete >(memory) {} 126 }; 127 128 } // namespace BPrivate 129 130 using BPrivate::ObjectDeleter; 131 using BPrivate::ArrayDeleter; 132 using BPrivate::MemoryDeleter; 133 134 #endif // _AUTO_DELETER_H 135