智能指针之手撕共享指针shared_ptr

要点

  • 成员是指向实例的指针和应用计数
  • 应用计数也应该是一个共享的int指针,因为这个计数需要各个共享指针同步维护
  • 需要重载的函数有:用指针构造;拷贝构造;赋值运算符=;解地址运算符*;指针调用成员的运算符->;析构函数;
  • 涉及到计数的部分:
    • 构造时初始化:1
    • 拷贝构造:+1
    • 赋值=:原有-1,新对象+1。注意-到0时,要执行析构;
    • 析构函数:-1。注意-到0时,要执行析构;

贴个代码

  #include <iostream>
  using namespace std;

  template <typename T>
  class SharePtr {
  private:
  	T* _ptr;
  	int* _count;
  public:
  	SharePtr(T* p) : _ptr(p), _count(new int(1)){}

  	SharePtr(const SharePtr<T>& sp) {
  		_ptr = sp._ptr;
  		_count = sp._count;
  		++(*_count);
  		return;
  	}

  	SharePtr<T>& operator=(const SharePtr<T>& sp) {
  		if ((--*(this->_count)) == 0) {
  			delete this->_count;
  			delete this->_ptr;
  		}
  		this->_ptr = sp->_ptr;
  		this->_count = sp->_count;
  		++(*(this->count));
  		return;
  	}

  	T& operator*() {
  		return *(this->_ptr);
  	}

  	T& operator->() {
  		return this->_ptr;
  	}

  	~SharePtr() {
  		if ((--*(this->_count)) == 0) {
  			delete this->_count;
  			this->_count = nullptr;
  			delete this->_ptr;
  			this->_ptr = nullptr;
  		}
  		return;
  	}

  	void show();
  };

  template<typename T>
  void SharePtr<T>::show() {
  	cout << this->_ptr << " " << this->_count << endl;
  	cout << *(this->_ptr) << " " << *(this->_count) << endl;
  	cout << endl;
  }

  int main()
  {
  	SharePtr<int> sp1(new int(1));
  	sp1.show();
  	SharePtr<int> sp2(sp1);
  	sp1.show();
  	SharePtr<int> sp3 = sp2;
  	sp2.show();
  	return 0;
  }
posted @ 2024-09-22 22:38  某糕  阅读(19)  评论(0编辑  收藏  举报