fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. template<typename T>
  6. class CAllocator
  7. {
  8. private:
  9. std::size_t size;
  10. T* data = nullptr;
  11.  
  12. public:
  13. typedef T* pointer;
  14. typedef const T* const_pointer;
  15.  
  16. typedef T& reference;
  17. typedef const T& const_reference;
  18.  
  19. typedef std::size_t size_type;
  20. typedef std::ptrdiff_t difference_type;
  21.  
  22. typedef T value_type;
  23.  
  24.  
  25. CAllocator() {}
  26. CAllocator(pointer data_ptr, size_type max_size) noexcept : size(max_size), data(data_ptr) {};
  27.  
  28. template<typename U>
  29. CAllocator(const CAllocator<U>& other) noexcept {};
  30.  
  31. CAllocator(const CAllocator &other) : size(other.size), data(other.data) {}
  32.  
  33. template<typename U>
  34. struct rebind {typedef CAllocator<U> other;};
  35.  
  36. pointer allocate(size_type n, const void* hint = 0) {return &data[0];}
  37. void deallocate(void* ptr, size_type n) {}
  38. size_type max_size() const {return size;}
  39. };
  40.  
  41. template <typename T, typename U>
  42. inline bool operator == (const CAllocator<T>&, const CAllocator<U>&) {return true;}
  43.  
  44. template <typename T, typename U>
  45. inline bool operator != (const CAllocator<T>& a, const CAllocator<U>& b) {return !(a == b);}
  46.  
  47. struct RepBase
  48. {
  49. std::size_t length;
  50. std::size_t capacity;
  51. std::int16_t refcount;
  52. };
  53.  
  54. int main()
  55. {
  56. typedef std::basic_string<char, std::char_traits<char>, CAllocator<char>> CAString;
  57.  
  58. const int size = 1024;
  59. char ptr[size] = {0};
  60.  
  61. CAString str(CAllocator<char>(&ptr[0], size));
  62. str.append("hello");
  63.  
  64. std::cout<<&ptr[sizeof(RepBase)];
  65. }
  66.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
hello