daily pastebin goal
49%
SHARE
TWEET

Untitled

a guest Feb 13th, 2018 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. class SharedPtr {
  5. private:
  6.     T* ptr;
  7.     size_t* ref_c;
  8.  
  9. public:
  10.     SharedPtr() : ptr(nullptr), ref_c(new size_t(1)) {}
  11.  
  12.     SharedPtr(T* p) : ptr(p), ref_c(new size_t(1)) {}
  13.  
  14.     SharedPtr(const SharedPtr& other) : ptr(other.ptr), ref_c() {
  15.         ref_c = other.ref_c;
  16.         ++(*ref_c);
  17.     }
  18.  
  19.     void swap(SharedPtr& other) {
  20.         std::swap(ptr, other.ptr);
  21.         std::swap(ref_c, other.ref_c);
  22.     }
  23.  
  24.     SharedPtr(SharedPtr&& other) {
  25.         this->swap(other);
  26.     }
  27.  
  28.     void reset(T* p) {
  29.         --(*ref_c);
  30.         ref_c = new size_t(1);
  31.         ptr = p;
  32.     }
  33.  
  34.     SharedPtr& operator =(T* p) {
  35.         this->reset(p);
  36.         return (*this);
  37.     }
  38.  
  39.     SharedPtr& operator =(const SharedPtr& other) {
  40.         --(*ref_c);
  41.         ptr = other.ptr;
  42.         ref_c = other.ref_c;
  43.         ++(*ref_c);
  44.         return (*this);
  45.     }
  46.  
  47.     SharedPtr& operator =(SharedPtr&& other) {
  48.         this->swap(other);
  49.         return (*this);
  50.     }
  51.  
  52.     const T& operator *() const {
  53.         return *ptr;
  54.     }
  55.  
  56.     T& operator *() {
  57.         return *ptr;
  58.     }
  59.  
  60.     T* operator ->() const {
  61.         return ptr;
  62.     }
  63.  
  64.     T* get() const {
  65.         return ptr;
  66.     }
  67.  
  68.     explicit operator bool() const {
  69.         return ptr == nullptr;
  70.     }
  71.  
  72.     ~SharedPtr() {
  73.         if (ref_c != nullptr && *ref_c <= 1) {
  74.             delete ptr;
  75.             delete ref_c;
  76.         } else {
  77.             if (ref_c != nullptr) {
  78.                 --(*ref_c);
  79.             }
  80.         }
  81.     }
  82. };
  83.  
  84. using namespace std;
  85.  
  86. int main()
  87. {
  88.     SharedPtr<int> x(new int(6));
  89.     SharedPtr<int> y(std::move(x));
  90.     cout << *y << endl;
  91.     return 0;
  92. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top