Untitled

 avatar
unknown
plain_text
24 days ago
1.4 kB
2
Indexable
#include<utility>
template <typename T>
class shared_pointer {
  long *count{nullptr};
  T *ptr{nullptr};
public:
    // Constructor
    explicit shared_pointer(T* raw_ptr = nullptr) :ptr(raw_ptr),count(new long(1))    {}

    // Copy Constructor
    shared_pointer(const shared_pointer& other) {
      ptr=other.ptr;
      count=other.count;
      ++*count;
    }

    void swap(shared_pointer &other){
      std::swap(ptr,other.ptr);
      std::swap(count,other.count);
    }

    // Assignment Operator
    shared_pointer& operator=(const shared_pointer& other) {
      if(this==&other) return *this;
      shared_pointer tmp{other};
      swap(tmp);
      return *this;
    }

    // Destructor
    ~shared_pointer() {
      if(--*count==0){
        delete ptr;
        delete count;
        ptr=nullptr;
        count=nullptr;
      }
    }

    // get(): Returns the raw pointer
    T* get() const {
      return ptr;
    }

    // use_count(): Returns the reference count
    int use_count() const {
      return *count;
    }

    // reset(): Releases ownership of the managed object
    void reset(T* new_ptr = nullptr) {
      shared_pointer tmp{new_ptr};
      swap(tmp);
      return;
    }

    // Dereference operator
    T& operator*() const {
      return *ptr;
    }

    // Member access operator
    T* operator->() const {
      return ptr;
    }
};
Leave a Comment