tool_mem.template.h 1.1 KB

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