Advertisement
hanni76

Untitled

Sep 5th, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. template<class T>
  2. struct SharedPtr
  3. {
  4. template<class P>
  5. struct Wrapper
  6. {
  7. P* ptr;
  8. long count;
  9.  
  10. Wrapper(P* ptr) : ptr(ptr), count(1)
  11. { if (ptr == nullptr ) throw "Invalid pointer"; }
  12.  
  13. ~Wrapper() { delete ptr; }
  14.  
  15. void addRef() { ++count; }
  16. void release()
  17. {
  18. if (--count == 0)
  19. {
  20. delete this;
  21. }
  22. }
  23. };
  24.  
  25. explicit SharedPtr(T *ptr = nullptr)
  26. : holder(ptr ? new Wrapper<T>(ptr) : nullptr)
  27. {
  28. }
  29.  
  30. SharedPtr(const SharedPtr<T>& other) : holder(nullptr)
  31. {
  32. copy(other);
  33. }
  34.  
  35. ~SharedPtr()
  36. {
  37. clear();
  38. }
  39.  
  40. SharedPtr& operator=(const SharedPtr<T>& other)
  41. {
  42. if (this != &other)
  43. {
  44. copy(other);
  45. }
  46. return *this;
  47. }
  48.  
  49. T* get() const { return holder ? holder->ptr : nullptr;}
  50.  
  51. void reset(T *ptr = nullptr)
  52. {
  53. clear();
  54.  
  55. if (ptr != nullptr)
  56. {
  57. holder = new Wrapper<T>(ptr);
  58. }
  59. }
  60.  
  61. const T& operator*() const
  62. {
  63. if (holder == nullptr) throw "Invalid pointer";
  64. return *holder->ptr;
  65. }
  66. T& operator*()
  67. {
  68. if (holder == nullptr) throw "Invalid pointer";
  69. return *holder->ptr;
  70. }
  71.  
  72. T* operator->() const
  73. {
  74. return get();
  75. }
  76.  
  77. private:
  78. void copy(const SharedPtr<T>& other)
  79. {
  80. clear();
  81.  
  82. if (other.holder)
  83. {
  84. holder = other.holder;
  85. holder->addRef();
  86. }
  87. }
  88.  
  89. void clear()
  90. {
  91. if (holder)
  92. {
  93. holder->release();
  94. holder = nullptr;
  95. }
  96. }
  97.  
  98. Wrapper<T> *holder;
  99. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement