ptr implement

unique_ptr

template<typename T>
class my_unique_ptr {
 public:
  my_unique_ptr() : ptr(nullptr) {}
  my_unique_ptr(T *ptr) : ptr(ptr) {}
  ~my_unique_ptr() {
    __cleanup__();
  }

  // copying is not permitted
  my_unique_ptr(const my_unique_ptr &ptr) = delete;
  my_unique_ptr &operator=(const my_unique_ptr &ptr) = delete;

  my_unique_ptr(my_unique_ptr &&another) {
    ptr = another.ptr;
    another.ptr = nullptr;
  }
  my_unique_ptr &operator=(my_unique_ptr &&another) {
    __cleanup__();
    ptr = another.ptr;
    another.ptr = nullptr;
  }

  // dereferencing
  T *operator->() const {
    return ptr;
  }

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

 private:
  void __cleanup__() {
    if (ptr != nullptr) {
      delete ptr;
    }
  }

  T *ptr;
};

shared_ptr

typedef unsigned int uint;
template<typename T>
class my_shared_ptr {
 public:
  my_shared_ptr() : ptr(nullptr), ref_count(new uint(0)) {}
  my_shared_ptr(T *ptr) : ptr(ptr), ref_count(new uint(1)) {}
  ~my_shared_ptr() {
    __cleanup__();
  }

  my_shared_ptr(const my_shared_ptr &another) {
    ptr = another.ptr;
    ref_count = another.ref_count;
    if (another.ptr != nullptr) {
      (*ref_count)++;
    }
  }
  my_shared_ptr &operator=(const my_shared_ptr &another) {
    __cleanup__();
    ptr = another.ptr;
    ref_count = another.ref_count;
    if (another.ptr != nullptr) {
      (*ref_count)++;
    }
  }

  my_shared_ptr(my_shared_ptr &&another) {
    ptr = another.ptr;
    ref_count = another.ref_count;
    another.ref_count = nullptr;
    another.ptr = nullptr;
  }
  my_shared_ptr &operator=(my_shared_ptr &&another) {
    __cleanup__();
    ptr = another.ptr;
    ref_count = another.ref_count;
    another.ref_count = nullptr;
    another.ptr = nullptr;
  }

  T *operator->() const {
    return ptr;
  }

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

  uint get_count() const {
    return *ref_count;
  }

  T *get() const {
    return ptr;
  }

 private:
  void __cleanup__() {
    (*ref_count)--;
    if (*ref_count == 0) {
      if (ptr != nullptr) {
        delete ptr;
      }
      delete ref_count;
    }
  }

  T *ptr = nullptr;

  // `ref_count` should be pointer pointing to heap memory,
  // to share reference count between different `shared_ptr` objects
  uint *ref_count = nullptr;
};
posted @ 2023-03-08 01:29  我在地狱  阅读(13)  评论(0编辑  收藏  举报