mgcpp
A C++ Math Library Based on CUDA
memory_resource.hpp
Go to the documentation of this file.
1 #ifndef MEMORY_RESOURCE_HPP
2 #define MEMORY_RESOURCE_HPP
3 
4 #include <atomic>
5 #include <cstddef>
6 
7 namespace mgcpp {
8 
9 enum class byte : unsigned char {};
10 
11 // Taken & modified from https://github.com/phalpern/CppCon2017Code
13  public:
14  virtual ~memory_resource() = default;
15 
16  void* allocate(size_t bytes) { return do_allocate(bytes); }
17  void deallocate(void* p, size_t bytes) { return do_deallocate(p, bytes); }
18 
19  // `is_equal` is needed because polymorphic allocators are sometimes
20  // produced as a result of type erasure. In that case, two different
21  // instances of a polymorphic_memory_resource may actually represent
22  // the same underlying allocator and should compare equal, even though
23  // their addresses are different.
24  bool is_equal(const memory_resource& other) const noexcept {
25  return do_is_equal(other);
26  }
27 
28  protected:
29  virtual void* do_allocate(size_t bytes) = 0;
30  virtual void do_deallocate(void* p, size_t bytes) = 0;
31  virtual bool do_is_equal(const memory_resource& other) const noexcept = 0;
32 };
33 
34 inline bool operator==(const memory_resource& a, const memory_resource& b) {
35  // Call `is_equal` rather than using address comparisons because some
36  // polymorphic allocators are produced as a result of type erasure. In
37  // that case, `a` and `b` may contain `memory_resource`s with different
38  // addresses which, nevertheless, should compare equal.
39  return &a == &b || a.is_equal(b);
40 }
41 
42 inline bool operator!=(const memory_resource& a, const memory_resource& b) {
43  return !(a == b);
44 }
45 
46 } // namespace mgcpp
47 
48 #endif // MEMORY_RESOURCE_HPP
bool is_equal(const memory_resource &other) const noexcept
Definition: memory_resource.hpp:24
Definition: adapter_base.hpp:12
bool operator!=(allocator< T1 > const &a, allocator< T2 > const &b)
Definition: memory_resource.hpp:12
byte
Definition: memory_resource.hpp:9
void deallocate(void *p, size_t bytes)
Definition: memory_resource.hpp:17
bool operator==(allocator< T1 > const &a, allocator< T2 > const &b)
void * allocate(size_t bytes)
Definition: memory_resource.hpp:16