template <class T> class SmartPointer {
public:
//普通構造函數, 設定T * ptr的值,並將引用計數設爲1
SmartPointer(T * ptr) {
ref = ptr;
ref_count = new unsigned;
*ref_count = 1;
}
//指針拷貝構造函數,新建一個指向已有對象的智能指針
//需要先設定ptr和ref_count
//設爲指向sptr的ptr和ref_count
//並且,因爲新建了一個ptr的引用,所以引用計數加一
SmartPointer(SmartPointer<T> &sptr) {
ref = sptr.ref;
ref_count = sptr.ref_count;
++(*ref_count);
}
//rewrite "="
SmartPointer<T> & operator = (SmartPointer<T> &sptr) {
//同一個指針,直接返回
if (this == &sptr)
return *this;
//如果計數值大於1,則舊指針計數值-1
if(*ref_count > 0)
remove();
//把舊指針值給新指針
ref = sptr.ref;
ref_count = sptr.ref_count;
//指針計數+1
++(*ref_count);
return *this;
}
~SmartPointer() {
remove();
}
T getValue() {
return *ref;
}
T getCount() {
return static_cast<T>(*ref_count);
}
protected:
//刪除指針
void remove() {
--(*ref_count);
//如果計數值等於0,則銷燬指針,並執行析構函數
if (*ref_count == 0) {
delete ref;
delete ref_count;
ref = NULL;
ref_count = NULL;
}
}
private:
unsigned * ref_count; //應用計數值
T * ref; //普通指針
};
21.手寫實現智能指針類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.