Eneboo - Documentación para desarrolladores
|
00001 /* -*- C++ -*- */ 00002 00003 #ifndef _UTILITY_H_ 00004 #define _UTILITY_H_ 00005 00026 #include <new.h> 00027 00028 00029 // Construct an object on a given heap. 00030 class newObject { 00031 public: 00032 template <class Heap, class Object> 00033 inline void operator() (Object*& o, Heap& h) const { 00034 o = new (h.malloc (sizeof(Object))) Object; 00035 } 00036 00037 template <class Heap, class Object, class A1> 00038 inline void operator() (Object*& o, const A1& a1, Heap& h) const { 00039 o = new (h.malloc (sizeof(Object))) Object (a1); 00040 } 00041 00042 template <class Heap, class Object, class A1, class A2> 00043 inline void operator() (Object*& o, const A1& a1, const A2& a2, Heap& h) const { 00044 o = new (h.malloc (sizeof(Object))) Object (a1, a2); 00045 } 00046 00047 template <class Heap, class Object, class A1, class A2, class A3> 00048 inline void operator() (Object*& o, const A1& a1, const A2& a2, const A3& a3, Heap& h) const { 00049 o = new (h.malloc (sizeof(Object))) Object (a1, a2, a3); 00050 } 00051 }; 00052 00053 00054 // Delete an object to a given heap. 00055 class deleteObject { 00056 public: 00057 template <class Heap, class Object> 00058 inline void operator()(Object*& o, Heap& h) { 00059 o->~Object(); 00060 h.free (o); 00061 } 00062 }; 00063 00064 00065 class newArray { 00066 public: 00067 template <class Heap, class Object> 00068 inline void operator() (Object*& o, unsigned int n, Heap& h) const { 00069 // Store the number of array elements in the beginning of the space. 00070 double * ptr = (double *) h.malloc (sizeof(Object) * n + sizeof(double)); 00071 *((unsigned int *) ptr) = n; 00072 // Initialize every element. 00073 ptr++; 00074 Object * ptr2 = (Object *) ptr; 00075 // Save the pointer to the start of the array. 00076 o = ptr2; 00077 // Now iterate and construct every object in place. 00078 for (unsigned int i = 0; i < n; i++) { 00079 new ((void *) ptr2) Object; 00080 ptr2++; 00081 } 00082 } 00083 }; 00084 00085 00086 class deleteArray { 00087 public: 00088 template <class Heap, class Object> 00089 inline void operator()(Object*& o, Heap& h) const { 00090 unsigned int n = *((unsigned int *) ((double *) o - 1)); 00091 Object * optr = o; 00092 // Call the destructor on every element in the array. 00093 for (unsigned int i = 0; i < n; i++) { 00094 optr->~Object(); 00095 optr++; 00096 } 00097 // Free the array. 00098 h.free ((void *) ((double *) o - 1)); 00099 } 00100 }; 00101 00102 #endif