fork download
  1. #ifndef CUSTOM_ALLCATOR_HPP
  2. #define CUSTOM_ALLCATOR_HPP
  3.  
  4. #include <cstdlib> // for malloc and free
  5. #include <memory> // for std::allocator
  6. #include <iostream> // for std::cout
  7.  
  8. namespace katahiromz {
  9.  
  10. template <typename T>
  11. class custom_allocator : public std::allocator<T> {
  12. public:
  13. typedef typename std::allocator<T>::size_type size_type;
  14. typedef typename std::allocator<T>::pointer pointer;
  15. typedef typename std::allocator<T>::const_pointer const_pointer;
  16. typedef typename std::allocator<T>::reference reference;
  17. typedef typename std::allocator<T>::const_reference const_reference;
  18. typedef typename std::allocator<T>::difference_type difference_type;
  19.  
  20. custom_allocator() {}
  21. custom_allocator(const custom_allocator<T>& x) {}
  22. template <typename U>
  23. custom_allocator(const custom_allocator<U>& x) {}
  24. pointer allocate(size_type count, const_pointer hinst = NULL) {
  25. size_type size = count * sizeof(T);
  26. std::cout << "custom_allocator: allocate " << size << std::endl;
  27. return reinterpret_cast<pointer>(std::malloc(size));
  28. }
  29. void deallocate(pointer ptr, size_type count) {
  30. std::cout << "custom_allocator: free " << ptr << std::endl;
  31. std::free(ptr);
  32. }
  33. template <typename U>
  34. struct rebind { typedef custom_allocator<U> other; };
  35. };
  36.  
  37. } // namespace katahiromz
  38.  
  39. #endif // ndef CUSTOM_ALLCATOR_HPP
  40.  
  41. #include <string>
  42. #include <vector>
  43. #include <map>
  44.  
  45. namespace katahiromz {
  46.  
  47. typedef std::basic_string<char, std::char_traits<char>,
  48. custom_allocator<char> > custom_string;
  49. typedef std::basic_string<wchar_t, std::char_traits<wchar_t>,
  50. custom_allocator<wchar_t> > custom_wstring;
  51.  
  52. template <typename T>
  53. using custom_vector = std::vector<T, custom_allocator<T> >;
  54.  
  55. template <typename KEY, typename VALUE, typename COMPARE = std::less<KEY> >
  56. using custom_map = std::map<KEY, VALUE, COMPARE,
  57. custom_allocator<std::pair<const KEY, VALUE> > >;
  58.  
  59. } // namespace katahiromz
  60.  
  61. int main(void) {
  62. katahiromz::custom_string str;
  63. str = "OK\n";
  64. str += "OK\n";
  65. std::cout << str << std::endl;
  66. katahiromz::custom_vector<int> vec;
  67. vec.push_back(2);
  68. vec.push_back(3);
  69. std::cout << vec[0] << std::endl;
  70. std::cout << vec[1] << std::endl;
  71. return 0;
  72. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
custom_allocator: allocate 16
custom_allocator: allocate 19
custom_allocator: free 
OK
OK

custom_allocator: allocate 4
custom_allocator: allocate 8
custom_allocator: free 0x934ea40
2
3
custom_allocator: free 0x934ea50
custom_allocator: free