Zserio C++ runtime library  1.0.0
Built for Zserio 2.13.0
MemoryResource.h
Go to the documentation of this file.
1 #ifndef ZSERIO_PMR_I_MEMORY_RESOURCE_H_INC
2 #define ZSERIO_PMR_I_MEMORY_RESOURCE_H_INC
3 
4 #include <cstddef>
5 #ifdef ZSERIO_MEMORY_RESOURCE_TRACING
6 # include <iostream>
7 #endif
8 
9 namespace zserio
10 {
11 namespace pmr
12 {
13 
18 {
19 public:
20  // this empty constructor is necessary for gcc 9.3.0 bug which causes test coverage failure
24  MemoryResource() = default;
25 
29  virtual ~MemoryResource() = default;
30 
35  MemoryResource(const MemoryResource& other) = delete;
36  MemoryResource(MemoryResource&& other) = delete;
37 
38  MemoryResource& operator=(const MemoryResource& other) = delete;
39  MemoryResource& operator=(MemoryResource&& other) = delete;
50  void* allocate(size_t bytes, size_t alignment = alignof(max_align_t))
51  {
52 #ifdef ZSERIO_MEMORY_RESOURCE_TRACING
53  void* const ptr = doAllocate(bytes, alignment);
54  std::cout << "MemoryResource::allocate bytes=" << bytes << " alignment=" << alignment << " -> " <<
55  std::hex << ptr << std::dec << std::endl;
56  return ptr;
57 #else
58  return doAllocate(bytes, alignment);
59 #endif
60  }
61 
71  void deallocate(void* p, size_t bytes, size_t alignment = alignof(max_align_t))
72  {
73 #ifdef ZSERIO_MEMORY_RESOURCE_TRACING
74  std::cout << "MemoryResource::deallocate p=" << std::hex << p << std::dec << " bytes=" << bytes <<
75  " alignment=" << alignment << std::endl;
76 #endif
77  doDeallocate(p, bytes, alignment);
78  }
79 
90  bool isEqual(const MemoryResource& other) const noexcept
91  {
92 #ifdef ZSERIO_MEMORY_RESOURCE_TRACING
93  std::cout << "MemoryResource::isEqual other=" << std::hex << &other << std::dec << std::endl;
94 #endif
95  return doIsEqual(other);
96  }
97 
98 private:
107  virtual void* doAllocate(size_t bytes, size_t alignment) = 0;
108 
118  virtual void doDeallocate(void* p, size_t bytes, size_t alignment) = 0;
119 
130  virtual bool doIsEqual(const MemoryResource& other) const noexcept = 0;
131 };
132 
141 inline bool operator==(const MemoryResource& lhs, const MemoryResource& rhs)
142 {
143  return &lhs == &rhs || lhs.isEqual(rhs);
144 }
145 
154 inline bool operator!=(const MemoryResource& lhs, const MemoryResource& rhs)
155 {
156  return !(lhs == rhs);
157 }
158 
169 
183 
184 } // namespace pmr
185 } // namespace zserio
186 
187 #endif // ZSERIO_PMR_I_MEMORY_RESOURCE_H_INC
bool operator==(const MemoryResource &lhs, const MemoryResource &rhs)
virtual ~MemoryResource()=default
MemoryResource & operator=(const MemoryResource &other)=delete
MemoryResource * getDefaultResource() noexcept
void * allocate(size_t bytes, size_t alignment=alignof(max_align_t))
bool operator!=(const MemoryResource &lhs, const MemoryResource &rhs)
MemoryResource * setDefaultResource(MemoryResource *resource) noexcept
bool isEqual(const MemoryResource &other) const noexcept
void deallocate(void *p, size_t bytes, size_t alignment=alignof(max_align_t))