Changeset 12706 for issm/trunk/src/c/shared/Alloc/xNewDelete.h
- Timestamp:
- 07/24/12 10:36:19 (13 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
issm/trunk/src/c/shared/Alloc/xNewDelete.h
r12330 r12706 8 8 #include <cassert> 9 9 10 11 // memory management of types 12 // T with non-trivial constructors require 13 // C++ style memory management 14 #define USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 15 // but for speed on may alternatively use C memory managment 16 // but can do so safely only for T that are at most 17 // plain old data structures (POD) 18 #ifndef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 19 #include <cstdlib> 20 #endif 21 10 22 template <class T> 11 23 T* xNew(unsigned int size) { 24 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 12 25 T* aT_p=new T[size]; 13 26 assert(aT_p); 14 27 return aT_p; 15 }; 28 #else 29 T* aT_p=(T*)malloc(size*sizeof(T)); 30 assert(aT_p); 31 return aT_p; 32 #endif 33 } 34 35 template <class T> 36 T* xNewZeroInit(unsigned int size) { 37 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 38 T* aT_p=xNew<T>(size); 39 for (unsigned int i=0; i<size;++i) 40 aT_p[i]=(T)0; 41 return aT_p; 42 #else 43 T* aT_p=(T*)calloc(size,sizeof(T)); 44 assert(aT_p); 45 return aT_p; 46 #endif 47 } 16 48 17 49 template <class T> 18 50 void xDelete(T*& aT_p) { 19 51 if (aT_p) 52 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 20 53 delete []aT_p; 54 #else 55 free((void*)aT_p); 56 #endif 21 57 aT_p=0; 22 }; 58 } 59 60 template <class T> 61 T* xReNew(T* old, unsigned int old_size, unsigned int size) { 62 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES 63 T* aT_p=0; 64 if (!old) { // no old memory 65 if (size) 66 aT_p=xNew<T>(size); // according to realloc behavior in manual page 67 } 68 else { // have old memory 69 if (!size) // but 0 size 70 xDelete<T>(old); // according to realloc behavior in manual page 71 else { // non-zero size 72 assert(old_size); // have old memory - need to have old_size set or this call is bad 73 // allocate new, delete old; ; even for the case when size is 74 // less than old_size we can't just keep the memory unchanged 75 // because otherwise classes that have ctors/dtors with side-effects 76 // may misbehave, for example classes with static instance/operations counters. 77 aT_p=xNew<T>(size); 78 unsigned int iMax=(old_size<size)?old_size:size; 79 for (unsigned int i=0; i<iMax;++i) { 80 // we need to copy the items by explicit assignments 81 aT_p[i]=old[i]; 82 } 83 xDelete<T>(old); 84 } 85 } 86 return aT_p; 87 #else 88 T* aT_p=0; 89 aT_p=(T*)realloc((void*)old,size*sizeof(T)); 90 if (size) 91 assert(aT_p); // according to realloc behavior in manual page 92 return aT_p; 93 #endif 94 } 23 95 24 96 #endif
Note:
See TracChangeset
for help on using the changeset viewer.