智慧指標之手撕共享指標shared_ptr

某糕發表於2024-09-22

要點

  • 成員是指向例項的指標和應用計數
  • 應用計數也應該是一個共享的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;
  }

相關文章