Advertisement
Guest User

Untitled

a guest
May 19th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. namespace stepik
  2. {
  3. template <typename T>
  4.   class shared_ptr
  5.   {
  6.   public:
  7.     shared_ptr(T *other = 0)
  8.     {
  9.         ptr = other;
  10.         if (ptr) link = new long(1);
  11.         else link = nullptr;
  12.  
  13.     }
  14.  
  15.     ~shared_ptr()
  16.     {
  17.       decrease();
  18.     }
  19.  
  20.     shared_ptr(const shared_ptr & other):ptr(other.ptr)
  21.     {
  22.         link = other.link;
  23.         if (link) *link += 1;
  24.     }
  25.  
  26.     shared_ptr& operator=(const shared_ptr & other)
  27.     {
  28.          if (this!=&other)
  29.         {
  30.             decrease();
  31.             ptr  =  other.ptr;
  32.             link = other.link;
  33.             if (link) ++(*link);
  34.  
  35.         }
  36.         return *this;
  37.     }
  38.  
  39.     explicit operator bool() const
  40.     {
  41.         return (ptr!=nullptr);
  42.     }
  43.  
  44.     T* get() const
  45.     {
  46.         return ptr;
  47.     }
  48.  
  49.     long use_count() const
  50.     {
  51.         if (link)
  52.         return *link;
  53.         else
  54.         return 0;
  55.     }
  56.  
  57.     T& operator*() const
  58.     {
  59.         return *ptr;
  60.     }
  61.  
  62.     T* operator->() const
  63.     {
  64.         return ptr;
  65.     }
  66.  
  67.     void swap(shared_ptr& x) noexcept
  68.     {
  69.          std::swap(ptr, x.ptr);
  70.          std::swap(link, x.link);
  71.     }
  72.  
  73.     void reset(T *otherptr = 0)
  74.     {
  75.         decrease();
  76.         ptr  = nullptr;
  77.         link = nullptr;
  78.         ptr = otherptr;
  79.         if (ptr) link = new long (1);
  80.         else link=nullptr;
  81.     }
  82.  
  83.   private:
  84.       T *ptr;
  85.       long* link;
  86.       void decrease ()
  87.       {
  88.           if (ptr && link && !(--(*link))){
  89.              delete ptr;
  90.              delete link;
  91.              link = 0;
  92.           }
  93.       }
  94.   };
  95. } // namespace stepik
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement