1
0

mem_block.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef _PFC_MEM_BLOCK_H_
  2. #define _PFC_MEM_BLOCK_H_
  3. class mem_block
  4. {
  5. private:
  6. void * data;
  7. int size;
  8. public:
  9. mem_block() {data=0;size=0;}
  10. ~mem_block() {if (data) free(data);}
  11. int get_size() const {return size;}
  12. void * get_ptr() const {return data;}
  13. void * set_size(int new_size)
  14. {
  15. if (data==0) data = malloc(size = new_size);
  16. else if (size!=new_size)
  17. {
  18. void * new_data = realloc(data,new_size);
  19. if (!new_data) return 0;
  20. data = new_data;
  21. size = new_size;
  22. }
  23. return data;
  24. }
  25. void * check_size(int new_size)
  26. {
  27. if (size<new_size) return set_size(new_size);
  28. else return data;
  29. }
  30. operator void * () const {return data;}
  31. };
  32. template<class T>
  33. class mem_block_t : private mem_block
  34. {
  35. public:
  36. int get_size() const {return mem_block::get_size()/sizeof(T);}
  37. T* get_ptr() const {return static_cast<T*>(mem_block::get_ptr());}
  38. T* set_size(int new_size) {return static_cast<T*>(mem_block::set_size(new_size*sizeof(T)));}
  39. T* check_size(int new_size) {return static_cast<T*>(mem_block::check_size(new_size*sizeof(T)));}
  40. operator T * () const {return get_ptr();}
  41. };
  42. #endif