Advertisement
Pashanze

Untitled

Mar 14th, 2022
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #pragma once
  2.  
  3. template<class T>
  4. struct ControlBlock {
  5.     size_t shared_count;
  6.     size_t weak_count;
  7.     T* object;
  8.  
  9.     template<class ... Args>
  10.     ControlBlock(size_t count, Args&& ... args) {
  11.  
  12.     };
  13. };
  14.  
  15.  
  16. template<class T>
  17. class Shared_Ptr {
  18.     T* ptr = nullptr;
  19.     size_t* count = nullptr;
  20.  
  21.     ControlBlock<T>* cptr = nullptr;
  22.  
  23.     template<class U, class ... Args>
  24.     friend Shared_Ptr<U> Make_Shared(Args&& ... args);
  25.    
  26.     Shared_Ptr(ControlBlock<T>* ptr) : cptr(ptr), ptr(ptr->object)
  27.     {
  28.  
  29.     }
  30.  
  31. public:
  32.     Shared_Ptr()
  33.     {
  34.  
  35.     }
  36.     explicit Shared_Ptr(T* ptr) : ptr(ptr), count(new int(1))
  37.     {
  38.  
  39.     }
  40.  
  41.     size_t use_count() const noexept;
  42.  
  43.     T* get() const noexept;
  44.  
  45.     ~Shared_Ptr()
  46.     {
  47.         if (!cptr) return;
  48.         --cptr->shared_count;
  49.  
  50.         if (cptr->shared_count == 0)
  51.         {
  52.             delete ptr;
  53.             if (cptr->weak_count == 0)
  54.             {
  55.                 delete cptr;
  56.             }
  57.         }
  58.     }
  59. };
  60.  
  61. template <class T, class ... Args>
  62. Shared_Ptr<T> Make_Shared(Args&& ... args)
  63. {
  64.     auto p = new ControlBlock<T>(1, std::forward<Args>(args)...);
  65.     return Shared_Ptr;
  66. }
  67.  
  68.  
  69. template<class T>
  70. class Weak_Ptr {
  71. private:
  72.     ControlBlock<T>* cptr = nullptr;
  73.  
  74. public:
  75.     Weak_Ptr(const Shared_Ptr<T>& p) : cptr(p.cptr)
  76.     {
  77.  
  78.     }
  79.  
  80.     bool expired() const
  81.     {
  82.         return cptr->shared_count == 0;
  83.     }
  84.  
  85.     Shared_Ptr<T> lock() const {
  86.         return Shared_Ptr<T>(cptr);
  87.     }
  88.  
  89.     ~Weak_Ptr()
  90.     {
  91.         if (!cptr)return;
  92.         --cptr->weak_count;
  93.         if (cptr->weak_count == 0 && cptr->shared_count == 0)
  94.         {
  95.             delete cptr;
  96.         }
  97.     }
  98. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement