Advertisement
Guest User

Untitled

a guest
May 25th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. struct counter {
  2. size_t shared_counter;
  3. size_t weak_counter;
  4. };
  5.  
  6.  
  7. template <typename T>
  8. class shared_ptr {
  9. public:
  10. shared_ptr() : shared_ptr{nullptr} {};
  11. shared_ptr(T* ptr);
  12.  
  13. shared_ptr(const shared_ptr& obj);
  14.  
  15. ~shared_ptr();
  16.  
  17. T& operator * () { return *obj_;}
  18.  
  19. private:
  20. shared_ptr(T* obj, counter* counter_);
  21.  
  22. void dealloc();
  23.  
  24. T* obj_;
  25. counter* counter_;
  26.  
  27. template <typename U>
  28. friend class weak_ptr;
  29. };
  30.  
  31. template <typename T>
  32. class weak_ptr {
  33. public:
  34. weak_ptr(const shared_ptr<T>& ptr);
  35. weak_ptr(const weak_ptr& ptr);
  36.  
  37. ~weak_ptr();
  38.  
  39. shared_ptr<T> shared();
  40. private:
  41. T* obj_;
  42. counter* counter_;
  43. };
  44.  
  45.  
  46.  
  47. template <typename T>
  48. weak_ptr<T>::weak_ptr(const shared_ptr<T>& ptr):
  49. obj_{ptr.obj_},
  50. counter_{ptr.counter_}
  51. {
  52. ++counter_->weak_counter;
  53. }
  54.  
  55. template <typename T>
  56. weak_ptr<T>::weak_ptr(const weak_ptr& ptr) :
  57. obj_{ptr.obj_},
  58. counter_{ptr.counter_}
  59. {
  60. ++counter_->weak_counter;
  61. }
  62.  
  63. template <typename T>
  64. weak_ptr<T>::~weak_ptr() {
  65. if (--counter_->weak_counter && !counter_->shared_counter) {
  66. delete counter_;
  67. }
  68. }
  69.  
  70. template <typename T>
  71. shared_ptr<T> weak_ptr<T>::shared() {
  72. return counter_->shared_counter == 0 ? shared_ptr<T>() : shared_ptr<T>(obj_, counter_);
  73. }
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80. template <typename T>
  81. shared_ptr<T>::shared_ptr(T* ptr) {
  82. obj_ = ptr;
  83. try {
  84. counter_ = new counter;
  85. } catch (...) {
  86. delete ptr;
  87. }
  88. counter_->shared_counter = 1;
  89. counter_->weak_counter = 0;
  90. }
  91.  
  92. template <typename T>
  93. shared_ptr<T>::shared_ptr(const shared_ptr& ptr) :
  94. obj_{ptr.obj_},
  95. counter_{ptr.counter_}
  96. {
  97. ++counter_->shared_counter;
  98. }
  99.  
  100. template <typename T>
  101. shared_ptr<T>::shared_ptr(T* obj, counter* counter) :
  102. obj_{obj},
  103. counter_{counter}
  104. {
  105. ++counter_->shared_counter;
  106. }
  107.  
  108. template <typename T>
  109. shared_ptr<T>::~shared_ptr() {
  110. dealloc();
  111. }
  112.  
  113. template <typename T>
  114. void shared_ptr<T>::dealloc() {
  115. if (counter_->shared_counter == 1 && counter_->weak_counter == 0) {
  116. delete counter_;
  117. } else {
  118. --counter_->shared_counter;
  119. }
  120.  
  121. if (obj_ != nullptr) {
  122. delete obj_;
  123. }
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement