Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #include <cassert>
  4. struct Expression;
  5. struct Number;
  6. struct BinaryOperation;
  7. struct FunctionCall;
  8. struct Variable;
  9.  
  10. struct pstorage
  11. {
  12.  
  13. pstorage(Expression *pt = 0) : ptr(pt)
  14. {
  15. if (pt == 0)
  16. count = 0;
  17.  
  18. else
  19. count = 1;
  20. }
  21. pstorage(Expression *pt, int count_) : ptr(pt), count(count_){}
  22.  
  23.  
  24. ~pstorage()
  25. {
  26. delete ptr;
  27. }
  28.  
  29. Expression *ptr;
  30. int count;
  31. };
  32.  
  33. struct SharedPtr
  34. {
  35. Expression& operator*() const {
  36. return *ptr_->ptr;
  37. }
  38. Expression* operator->() const {
  39. return ptr_->ptr;
  40. }
  41.  
  42.  
  43. // реализуйте следующие методы
  44. //
  45. explicit SharedPtr(Expression *ptr = 0) {
  46. if (ptr != 0)
  47. ptr_ = new pstorage(ptr);
  48. else ptr_ = 0;
  49.  
  50. }
  51.  
  52. ~SharedPtr() {
  53. if (ptr_ != 0)
  54. {
  55. ptr_->count--;
  56. if (ptr_->count <= 0)
  57. {
  58. delete ptr_;
  59.  
  60. }
  61. }
  62. }
  63.  
  64. SharedPtr(const SharedPtr &a) {
  65.  
  66.  
  67. if (a.ptr_ != 0)
  68. {
  69. ptr_ = a.ptr_;
  70. ptr_->count++;
  71. }
  72. else
  73. ptr_ = 0;
  74. }
  75.  
  76. SharedPtr& operator=(const SharedPtr &a) {
  77.  
  78. if (this==&a || a.ptr_ == ptr_) return *this;
  79.  
  80. if(a.ptr_ == 0) {
  81. if(ptr_ != 0) {
  82. ptr_->count--;
  83. if(ptr_->count == 0)
  84. delete ptr_;
  85. };
  86. ptr_ = a.ptr_;
  87. return *this;
  88. }
  89. else
  90. {
  91. if(ptr_ != 0) {
  92. ptr_->count--;
  93. if(ptr_->ptr==0)
  94. delete ptr_;
  95. ptr_ = a.ptr_;
  96. ptr_->count++;
  97. return *this;
  98. }
  99. else
  100. {
  101. ptr_ = a.ptr_;
  102. ptr_->count++;
  103. return *this;
  104. }
  105. };
  106.  
  107. }
  108.  
  109. Expression* get() const {
  110. if (ptr_ != 0)
  111. return ptr_->ptr;
  112. else return 0;
  113.  
  114. }
  115. void reset(Expression *ptr = 0) {
  116. if(ptr_ != 0 && ptr == ptr_->ptr)
  117. return;
  118. if (ptr == 0) {
  119. if(ptr_ != 0) {
  120. ptr_->count--;
  121. if(ptr_->count == 0)
  122. delete ptr_;
  123. }
  124. ptr_ = 0;
  125. }
  126. else {
  127. if(ptr_ != 0) {
  128. ptr_->count--;
  129. if(ptr_->count == 0)
  130. delete ptr_;
  131. }
  132. ptr_ = new pstorage(ptr);
  133. }
  134. }
  135. pstorage *ptr_;
  136. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement