mem.template.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #ifndef AFUN_MEM_TEMPLATE_H
  2. #define AFUN_MEM_TEMPLATE_H
  3. #include <cstdlib>
  4. #include "log.h"
  5. #include "tool-exit.h"
  6. #include "tool-logger.h"
  7. /* 取代calloc函数 */
  8. namespace aFuntool {
  9. template <typename T = void *>
  10. T *safeFree(T *ptr) {if (ptr != nullptr) free((void *)ptr); return nullptr;}
  11. template <typename T = void *>
  12. T *safeCalloc(size_t n, size_t size){
  13. T *re = (T *)calloc(n, size);
  14. if (re == nullptr) {
  15. if (aFunSysLogger)
  16. fatalErrorLog(aFunSysLogger, EXIT_FAILURE, "The memory error");
  17. else
  18. aFunExit(EXIT_FAILURE);
  19. }
  20. return re;
  21. }
  22. template <typename T = void *>
  23. T *safeCalloc(size_t n = 1){
  24. T *re = (T *)calloc(n, sizeof(T)); // 自动推断类型
  25. if (re == nullptr) {
  26. if (aFunSysLogger)
  27. fatalErrorLog(aFunSysLogger, EXIT_FAILURE, "The memory error");
  28. else
  29. aFunExit(EXIT_FAILURE);
  30. }
  31. return re;
  32. }
  33. }
  34. #endif //AFUN_MEM_TEMPLATE_H