sys_alloc.h 761 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #pragma once
  2. #include <util/system/compiler.h>
  3. #include <cstdlib>
  4. #include <new>
  5. inline void* y_allocate(size_t n) {
  6. void* r = malloc(n);
  7. if (r == nullptr) {
  8. throw std::bad_alloc();
  9. }
  10. return r;
  11. }
  12. inline void y_deallocate(void* p) {
  13. free(p);
  14. }
  15. /**
  16. * Behavior of realloc from C++99 to C++11 changed (http://www.cplusplus.com/reference/cstdlib/realloc/).
  17. *
  18. * Our implementation work as C++99: if new_sz == 0 free will be called on 'p' and nullptr returned.
  19. */
  20. inline void* y_reallocate(void* p, size_t new_sz) {
  21. if (!new_sz) {
  22. if (p) {
  23. free(p);
  24. }
  25. return nullptr;
  26. }
  27. void* r = realloc(p, new_sz);
  28. if (r == nullptr) {
  29. throw std::bad_alloc();
  30. }
  31. return r;
  32. }