Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #include <memory>
  2. #include <iostream>
  3. #include <vector>
  4. #include <limits>
  5. using namespace std;
  6.  
  7. template<class T>
  8. class TrackingAllocator
  9. {
  10. public:
  11. using value_type = T;
  12.  
  13. using pointer = T *;
  14. using const_pointer = const T *;
  15.  
  16. using void_pointer = void *;
  17. using const_void_pointer = const void*;
  18.  
  19. using size_type = size_t;
  20.  
  21. using difference_type = std::ptrdiff_t;
  22.  
  23. template<class U>
  24. struct rebind
  25. {
  26. using other = TrackingAllocator<U>;
  27. };
  28.  
  29. TrackingAllocator() = default;
  30.  
  31. template<class U>
  32. TrackingAllocator(const TrackingAllocator<U> &other) {}
  33.  
  34. ~TrackingAllocator() = default;
  35.  
  36. pointer allocate(size_type numObjects)
  37. {
  38. mAllocations += numObjects;
  39. return static_cast<pointer>(operator new(sizeof(T)*numObjects));
  40. }
  41.  
  42. pointer allocate(size_type numObjects, const_void_pointer hint)
  43. {
  44. return allocate(numObjects);
  45. }
  46.  
  47. void deallocate(pointer p, size_type numObjects)
  48. {
  49. operator delete(p);
  50. }
  51.  
  52. size_type max_size() const
  53. {
  54. return numeric_limits<size_type>::max();
  55. }
  56.  
  57. template<class U, class... Args>
  58. void construct(U *p, Args && ...args)
  59. {
  60. new(p) U(forward<Args>(args)...);
  61. }
  62.  
  63. template<class U>
  64. void destroy(U *p)
  65. {
  66. p->~U();
  67. }
  68.  
  69. size_type get_allocations() const
  70. {
  71. return mAllocations;
  72. }
  73.  
  74. private:
  75. static size_type mAllocations;
  76.  
  77. };
  78.  
  79. template<class T>
  80. typename TrackingAllocator<T>::size_type TrackingAllocator<T>::mAllocations = 0;
  81.  
  82. int main () {
  83.  
  84. using TAint = TrackingAllocator<int>;
  85. using TAdouble = TAint::rebind<double>::other;
  86.  
  87. vector<int, TrackingAllocator<int>> v(5);
  88. cout << v.get_allocator().get_allocations() << endl;
  89. cout << v.get_allocator().max_size() << endl;
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement