1. 程式人生 > >C++ 智能指針的簡單實現

C++ 智能指針的簡單實現

lse temp 如何實現 template 負責 delete 具體實現 inf 直接

  • 智能指針的用處:在c++中,使用普通指針容易造成堆內存的泄露問題,即程序員會忘記釋放,以及二次釋放,程序發生異常時內存泄漏等問題,而使用智能指針可以更好的管理堆內存。註意,在這裏智能指針是一個類而非真正的指針,只是對一個真正的指針進行包裝,代理原指針。通過操作符的重載,可以讓智能指針和真正的指針有類似的操作。
  • 如何實現:在智能指針析構函數當中,可以對代理的原指針進行delete以及賦空指針等操作,智能指針銷毀時,自動調用析構函數,省去了程序員自己管理指針的操作。當多個智能指針代理同一個指針時,我們要引入一個計數器,用來計數智能指針的個數,最後一個銷毀的智能指針有義務對原指針進行銷毀工作,具體實現代碼如下:

template<class T>
class Smart_ptr {
public:
    Smart_ptr(T*ptr);
    Smart_ptr(const Smart_ptr &ptr);//拷貝構造函數
    ~Smart_ptr();//析構函數
    int get_cnt();//獲得當前代理原指針的智能指針個數
    Smart_ptr& operator=(const Smart_ptr&ptr);//賦值操作
    T& operator *();//指針操作
    T* operator ->();//指針操作
private
: T*_ptr; int*_cnt; }; template<class T> Smart_ptr<T>::Smart_ptr(T*ptr):_ptr(ptr) {//判斷參數指針是否為空;不為空,計數+1 if (_ptr) _cnt = new int(1); else _cnt = new int(0); } template<class T> Smart_ptr<T>::Smart_ptr(const Smart_ptr &ptr) {//復制構造函數,復制成功,計數加1 if (this != &ptr) {
this->_ptr = ptr._ptr; this->_cnt = ptr._cnt; (*this->_cnt)++; } } template<class T> Smart_ptr<T>::~Smart_ptr() {//若當前的智能指針是最後一個代理指針,負責銷毀原指針 (*this->_cnt)--; if ((*this->_cnt) == 0) { delete this->_cnt; delete this->_ptr; _cnt = nullptr; _ptr = nullptr; } } template<class T> Smart_ptr<T>& Smart_ptr<T>::operator=(const Smart_ptr&ptr) {//1:若賦值前後代理的指針是一樣的,直接返回即可2:先判斷當前的智能指針是否為最後一個代理原指針的智能指針,若是,銷毀原指針; if (this->_ptr == ptr._ptr)return *this;//3:當前智能指針將代理一個新的指針 if (this->_ptr != nullptr) { (*this->_cnt)--; if (*this->_cnt == 0) { delete this->_cnt; delete this->_ptr; } } this->_cnt = ptr._cnt; this->_ptr = ptr._ptr; (*this->_cnt)++; return *this; } template<class T> T& Smart_ptr<T>::operator *() {//指針操作 return *(this->_ptr); } template<class T> T* Smart_ptr<T>::operator->() {//指針操作 return this->_ptr; } template<class T> int Smart_ptr<T>::get_cnt() { return *this->_cnt; }

main函數:

int main() {
    Smart_ptr<int>sp1(new int(1));
    cout <<"sp1.cnt:"<< sp1.get_cnt() << endl;
    Smart_ptr<int>sp2(sp1);
    cout << "sp1.cnt:" << sp1.get_cnt() << endl;
    Smart_ptr<int>sp3(new int(10));
    cout << "sp3.cnt:" << sp3.get_cnt() << endl;;
    sp3 = sp2;
    cout << "sp3.cnt:" << sp3.get_cnt() << endl;
    return 0;
}

調用結果:

技術分享圖片

C++ 智能指針的簡單實現