Geant4 Cross Reference |
1 #ifndef tools_realloc 1 #ifndef tools_realloc 2 #define tools_realloc 2 #define tools_realloc 3 3 4 #include <cstring> //memcpy 4 #include <cstring> //memcpy 5 5 6 namespace tools { 6 namespace tools { 7 7 8 template <class T> 8 template <class T> 9 inline bool realloc(T*& a_pointer,size_t a_new 9 inline bool realloc(T*& a_pointer,size_t a_new_size,size_t a_old_size,bool a_init = false) { 10 if(!a_new_size) { 10 if(!a_new_size) { 11 delete [] a_pointer; 11 delete [] a_pointer; 12 a_pointer = 0; 12 a_pointer = 0; 13 return true; 13 return true; 14 } 14 } 15 if(!a_pointer) { 15 if(!a_pointer) { 16 a_pointer = new T[a_new_size]; 16 a_pointer = new T[a_new_size]; 17 if(!a_pointer) return false; 17 if(!a_pointer) return false; 18 return true; 18 return true; 19 } 19 } 20 if(a_old_size==a_new_size) return true; 20 if(a_old_size==a_new_size) return true; 21 T* pointer = new T[a_new_size]; 21 T* pointer = new T[a_new_size]; 22 if(!pointer) { 22 if(!pointer) { 23 delete [] a_pointer; 23 delete [] a_pointer; 24 a_pointer = 0; 24 a_pointer = 0; 25 return false; 25 return false; 26 } 26 } 27 if(a_new_size>a_old_size) { 27 if(a_new_size>a_old_size) { 28 ::memcpy(pointer,a_pointer,a_old_size*size 28 ::memcpy(pointer,a_pointer,a_old_size*sizeof(T)); 29 if(a_init){ 29 if(a_init){ 30 size_t num = a_new_size-a_old_size; 30 size_t num = a_new_size-a_old_size; 31 T* pos = pointer+a_old_size; 31 T* pos = pointer+a_old_size; 32 for(size_t i=0;i<num;i++,pos++) *pos = T 32 for(size_t i=0;i<num;i++,pos++) *pos = T(); 33 } 33 } 34 } else { 34 } else { 35 ::memcpy(pointer,a_pointer,a_new_size*size 35 ::memcpy(pointer,a_pointer,a_new_size*sizeof(T)); 36 } 36 } 37 delete [] a_pointer; 37 delete [] a_pointer; 38 a_pointer = pointer; 38 a_pointer = pointer; 39 return true; 39 return true; 40 } 40 } 41 41 42 } 42 } 43 43 44 #endif 44 #endif