Advertisement
hanni76

Untitled

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