mem.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #ifndef TRYMEM_H
  2. #define TRYMEM_H
  3. #include "exception.h"
  4. #include <malloc.h>
  5. namespace binom {
  6. void tryFree(void* ptr);
  7. template <typename Type>
  8. Type* tryMalloc() {
  9. Type* ptr = reinterpret_cast<Type*>(malloc(sizeof(Type)));
  10. if(ptr == nullptr) throw binom::Exception(binom::ErrCode::memory_allocation_error, "Memory type allocation error!");
  11. else return ptr;
  12. }
  13. void* tryMalloc(size_t size);
  14. template <typename Type>
  15. Type* tryMalloc(size_t count) {
  16. if(!count) return nullptr;
  17. Type* ptr = reinterpret_cast<Type*>(malloc(sizeof (Type) * count));
  18. if(ptr == nullptr) throw binom::Exception(binom::ErrCode::memory_allocation_error, "Memory array allocation error!");
  19. else return ptr;
  20. }
  21. void* tryRealloc(void* ptr, size_t size);
  22. template <typename Type>
  23. Type* tryRealloc(Type* ptr, size_t count) {
  24. if(!count) {
  25. tryFree(ptr);
  26. return nullptr;
  27. }
  28. Type* new_ptr = reinterpret_cast<Type*>(realloc(ptr, sizeof (Type) * count));
  29. if(new_ptr == nullptr) throw binom::Exception(binom::ErrCode::memory_allocation_error, "Memory array allocation error!");
  30. else return new_ptr;
  31. }
  32. }
  33. #endif // TRYMEM_H