alloc_utils.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
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #ifndef PLANCK_ALLOC_UTILS_H
00033 #define PLANCK_ALLOC_UTILS_H
00034
00035 #include <cstdlib>
00036 #include <cstddef>
00037 #include "datatypes.h"
00038
00039 template <typename T> class normalAlloc__
00040 {
00041 public:
00042 static T *alloc(tsize sz) { return (sz>0) ? new T[sz] : 0; }
00043 static void dealloc (T *ptr) { delete[] ptr; }
00044 };
00045
00046 template <typename T, int align> class alignAlloc__
00047 {
00048 private:
00049
00050
00051
00052 enum { max_nat_align = sizeof(void *) };
00053
00054
00055 public:
00056 static T *alloc(tsize sz)
00057 {
00058 using namespace std;
00059 if (sz==0) return 0;
00060 planck_assert((align&(align-1))==0,"alignment must be power of 2");
00061 void *res;
00062 if (align<=max_nat_align)
00063 {
00064 res=malloc(sz*sizeof(T));
00065 planck_assert(res!=0,"error in malloc()");
00066 }
00067 else
00068 {
00069 tsize overhead=align-1+sizeof(void*);
00070 void *ptr=malloc(sz*sizeof(T)+overhead);
00071 planck_assert(ptr!=0,"error in malloc()");
00072 tsize sptr=reinterpret_cast<tsize>(ptr);
00073 sptr = (sptr+overhead) & ~(align-1);
00074 void **ptr2 = reinterpret_cast<void **>(sptr);
00075 ptr2[-1]=ptr;
00076 res=ptr2;
00077 }
00078 return static_cast<T *>(res);
00079 }
00080 static void dealloc(T *ptr)
00081 {
00082 using namespace std;
00083 if (align<=max_nat_align)
00084 free(ptr);
00085 else
00086 {
00087 if (ptr==0) return;
00088 void **ptr2 = reinterpret_cast<void **>(ptr);
00089 free (ptr2[-1]);
00090 }
00091 }
00092 };
00093
00094 #endif