下面實(shí)現(xiàn)一個(gè)指向int的智能指針。 sub為輔助類,用于存儲(chǔ)指針引用的狀態(tài)料滥。所有成員都是私有的,僅供autoptr類調(diào)用艾船。
class sub{
int * ptr;
int count;
friend class autoptr;
sub(int * p) :ptr(p), count(1){}
~sub(){
if (--count == 0)
delete ptr;
}
};
class autoptr{
public:
autoptr(int * pBase) : psub(new sub(pBase)) {}
autoptr(const autoptr & autop) : psub(autop.psub) { ++psub->count; }
autoptr & operator = (const autoptr & autop){
if (--psub->count == 0)//等號(hào)左側(cè)減引用
delete psub;
psub = autop.psub;
++psub->count;//增加原等號(hào)右側(cè)引用數(shù)
return *this;
}
private:
sub* psub;
};
int main(){
int * p1 = new int(1);
int * p2 = new int(2);
autoptr ptr1(p1);
autoptr ptr2(ap1);
autoptr ptr3(p2);
ptr3= ptr2;
return 0;
}
智能指針實(shí)現(xiàn)的結(jié)構(gòu)如下圖所示: