tracked_memory_resource.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef ENTT_COMMON_TRACKED_MEMORY_RESOURCE_HPP
  2. #define ENTT_COMMON_TRACKED_MEMORY_RESOURCE_HPP
  3. #if __has_include(<version>)
  4. # include <version>
  5. #
  6. # if defined(__cpp_lib_memory_resource) && __cpp_lib_memory_resource >= 201603L
  7. # define ENTT_HAS_TRACKED_MEMORY_RESOURCE
  8. #
  9. # include <cstddef>
  10. # include <memory_resource>
  11. # include <string>
  12. namespace test {
  13. class tracked_memory_resource: public std::pmr::memory_resource {
  14. void *do_allocate(std::size_t bytes, std::size_t alignment) override {
  15. ++alloc_counter;
  16. return std::pmr::get_default_resource()->allocate(bytes, alignment);
  17. }
  18. void do_deallocate(void *value, std::size_t bytes, std::size_t alignment) override {
  19. ++dealloc_counter;
  20. std::pmr::get_default_resource()->deallocate(value, bytes, alignment);
  21. }
  22. bool do_is_equal(const std::pmr::memory_resource &other) const noexcept override {
  23. return (this == &other);
  24. }
  25. public:
  26. using string_type = std::pmr::string;
  27. using size_type = std::size_t;
  28. static constexpr const char *default_value = "a string long enough to force an allocation (hopefully)";
  29. tracked_memory_resource()
  30. : alloc_counter{},
  31. dealloc_counter{} {}
  32. size_type do_allocate_counter() const noexcept {
  33. return alloc_counter;
  34. }
  35. size_type do_deallocate_counter() const noexcept {
  36. return dealloc_counter;
  37. }
  38. void reset() noexcept {
  39. alloc_counter = 0u;
  40. dealloc_counter = 0u;
  41. }
  42. private:
  43. size_type alloc_counter;
  44. size_type dealloc_counter;
  45. };
  46. } // namespace test
  47. # endif
  48. #endif
  49. #endif