手动实现范例:
template <class T>
class MyPointer {
public:
//普通构造函数, 设定T * ptr的值,并将引用计数设为1
MyPointer(T * ptr) {
ref = ptr;
ref_count = new unsigned;
*ref_count = 1;
}
//copy construct;
MyPointer(MyPointer<T> &sptr) {
ref = sptr.ref;
ref_count = sptr.ref_count;
++(*ref_count);
}
//rewrite construct;
MyPointer<T> & operator = (MyPointer<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;
}
//deconstruct;
~MyPointer() {
remove();
}
T getValue() {
return *ref;
}
T getCount() {
return static_cast<T>(*ref_count);
}
protected:
//delete ref;
void remove() {
--(*ref_count);
//如果ref_count等于0,则销毁指针,并执行析构函数
if (*ref_count == 0) {
delete ref;
delete ref_count;
ref = NULL;
ref_count = NULL;
}
}
private:
unsigned * ref_count; //应用计数值
T * ref; //普通指针
};