fork download
  1. #include <cstddef>
  2. #include <cstdlib>
  3. #include <limits>
  4. #include <utility>
  5. #include <vector>
  6.  
  7. template <typename T>
  8. class mallocator // because malloc and allocator :O
  9. {
  10. public:
  11. typedef T value_type;
  12. typedef value_type * pointer;
  13. typedef value_type const * const_pointer;
  14. typedef value_type & reference;
  15. typedef value_type const & const_reference;
  16. typedef std::size_t size_type;
  17. typedef std::ptrdiff_t difference_type;
  18.  
  19. template <typename U>
  20. struct rebind
  21. {
  22. typedef mallocator<U> other;
  23. };
  24.  
  25. inline explicit mallocator() {}
  26. inline ~mallocator() {}
  27. inline explicit mallocator(mallocator const &) {}
  28. template <typename U>
  29. inline explicit mallocator(mallocator<U> const &) {}
  30.  
  31. inline pointer address(reference r) { return std::addressof(r); }
  32. inline const_pointer address(const_reference r) { return std::addressof(r); }
  33.  
  34. inline pointer allocate(size_type cnt, void const * = nullptr)
  35. {
  36. return std::malloc(cnt * sizeof(value_type));
  37. }
  38.  
  39. inline void deallocate(pointer p, size_type)
  40. {
  41. std::free(p);
  42. }
  43.  
  44. inline size_type max_size() const
  45. {
  46. return std::numeric_limits<size_type>::max() / sizeof(T);
  47. }
  48.  
  49. inline void construct(pointer p, const_reference t) { new(p) T(t); }
  50. inline void destroy(pointer p) { p->~T(); }
  51.  
  52. inline bool operator == (mallocator const &) { return true; }
  53. inline bool operator != (mallocator const &) { return false; }
  54. };
  55.  
  56. template <typename Type, typename Allocator>
  57. class raw_vector
  58. : public std::vector<Type, Allocator>
  59. {
  60. using std::vector<Type, Allocator>::_Vector_base::_M_impl;
  61.  
  62. public:
  63. template <typename Iterator>
  64. raw_vector(Iterator start, Iterator end, Allocator const & a = Allocator())
  65. : std::vector<Type, Allocator>(a)
  66. {
  67. // implementation defined
  68. _M_impl._M_start = start;
  69. _M_impl._M_finish = _M_impl._M_end_of_storage = end;
  70. }
  71. };
  72.  
  73. int main()
  74. {
  75. char * foo = static_cast<char *>(std::malloc(12));
  76. // no deep copy here:
  77. raw_vector<char, mallocator<char>> raw(foo, foo + 12);
  78. // still no deep copy
  79. std::vector<char, mallocator<char>> normal(std::move(raw));
  80. // mallocator is important, so std::free is used instead of delete[]
  81. return 0;
  82. }
Success #stdin #stdout 0s 3408KB
stdin
Standard input is empty
stdout
Standard output is empty