Advertisement
bogolyubskiyalexey

Untitled

Mar 12th, 2021
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. template<typename T>
  2. class MySharedPtr {
  3. private:
  4.     size_t* n = nullptr;
  5.     T* ptr = nullptr;
  6.  
  7.  
  8. public:
  9.     void release() {
  10.         if (n) {
  11.             if (*n == 1) {
  12.                 delete n;
  13.                 delete ptr;
  14.             } else {
  15.                 --*n;
  16.             }
  17.         }
  18.         n = nullptr;
  19.         ptr = nullptr;
  20.     }
  21.     MySharedPtr() = default;
  22.    
  23.     MySharedPtr(const MySharedPtr<T>& other) :
  24.         ptr(other.ptr),
  25.         n(other.n)
  26.     {
  27.         if (n) {
  28.             ++*n;
  29.         }
  30.     }
  31.    
  32.     MySharedPtr(MySharedPtr<T>&& other) :
  33.         ptr(other.ptr),
  34.         n(other.n)
  35.     {
  36.         other.ptr = nullptr;
  37.         other.n = nullptr;
  38.     }
  39.    
  40.     MySharedPtr(T* new_ptr) :
  41.         ptr(new_ptr),
  42.         n(new size_t(1)) {
  43.     }
  44.    
  45.     ~MySharedPtr() {
  46.         release();
  47.     }
  48.    
  49.     T& operator*() {
  50.         return *ptr;
  51.     }
  52.     const T& operator*() const {
  53.         return *ptr;
  54.     }
  55.    
  56.     MySharedPtr<T>& operator= (const MySharedPtr<T>& other) {
  57.         if (&other == this) {
  58.             return *this;
  59.         }
  60.         release();
  61.        
  62.         n = other.n;
  63.         ptr = other.ptr;
  64.         if (n) {
  65.             ++*n;
  66.         }
  67.         return *this;
  68.     }
  69.    
  70.    
  71.     MySharedPtr<T>& operator= (MySharedPtr<T>&& other) {
  72.         if (&other == this) {
  73.             return *this;
  74.         }
  75.         release();
  76.         n = other.n;
  77.         ptr = other.ptr;
  78.         other.n = nullptr;
  79.         other.ptr = nullptr;
  80.         return *this;
  81.     }
  82.    
  83. };
  84. MySharedPtr<int> A(new int); // n = 1
  85. MySharedPtr<int> B(std::move(A)); //
  86. int& ref = *B;
  87.  
  88. A = std::move(B);
  89.  
  90. MySharedPtr<int> p(new int(10));  // n = 1
  91. MySharedPtr<int> a(p);            // n = 2
  92. MySharedPtr<int> c(p);            // n = 3
  93.  
  94. MySharedPtr<int> p1(new int(9));  // n = 1
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement