fork download
  1. /** Trying this again. Simpler approach, maybe...
  2. **/
  3.  
  4. #include <cstddef>
  5. #include <limits>
  6. #include <new>
  7. #include <stdexcept>
  8. #include <iostream>
  9. #include <cstdlib>
  10.  
  11. template <typename T> class MemoryManager
  12. {
  13. public:
  14. /** Typedefs **/
  15. typedef T * pointer;
  16. typedef const T * const_pointer;
  17. typedef T& reference;
  18. typedef const T& const_reference;
  19. typedef T value_type;
  20. typedef size_t size_type;
  21. typedef ptrdiff_t difference_type;
  22.  
  23. T* allocate(size_t n) const;
  24. void deallocate(T* const buffer, size_t) const;
  25. void construct(T* const ptr, const T& value) const;
  26. size_t max_size() const;
  27. MemoryManager() {};
  28.  
  29. template <typename U> struct rebind
  30. {
  31. typedef MemoryManager<U> other;
  32. };
  33. };
  34.  
  35. template <typename T>
  36. T* MemoryManager<T>::allocate(size_t n) const
  37. {
  38. if(n == 0)
  39. return NULL;
  40.  
  41. if(n > max_size())
  42. {
  43. throw std::length_error("Integer overflow at MemoryManager::allocate()");
  44. }
  45.  
  46. T* buffer = static_cast<T*>(malloc(n * sizeof(T)));
  47.  
  48. if(buffer == NULL)
  49. {
  50. throw std::bad_alloc();
  51. }
  52.  
  53. std::cout << (n * sizeof(T)) << " bytes allocated.\n";
  54. return buffer;
  55. }
  56.  
  57. template <typename T>
  58. void MemoryManager<T>::deallocate(T* const buffer, size_t) const
  59. {
  60. free(buffer);
  61. std::cout << "Buffer deallocated.\n";
  62. }
  63.  
  64. template <typename T>
  65. void MemoryManager<T>::construct(T* const ptr, const T& value) const
  66. {
  67. void* const placement = static_cast<void*>(ptr);
  68. new (placement) T(value);
  69. }
  70.  
  71. template <typename T>
  72. size_t MemoryManager<T>::max_size() const
  73. {
  74. return std::numeric_limits<size_t>::max();
  75. }
  76.  
  77. #include <vector>
  78. #include <iostream>
  79. int main()
  80. {
  81. auto f = [&](int i){std::cout<< i << "\t";};
  82.  
  83. std::vector<int, MemoryManager<int> > v = {1,2,3,4,5};
  84.  
  85. for(int i : v)
  86. {
  87. f(i);
  88. }
  89. }
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
20 bytes allocated.
1	2	3	4	5	Buffer deallocated.