您的位置:首页 > 其它

智能指针与弱引用详解

2013-09-26 09:28 633 查看
Template <typename T>

class SmartPtr{

public:

SmartPtr(T *p = 0):ptr(p){count = new int(1) ;}// 第一次创建的时候,引数肯定是1

SmartPtr(const SmartPtr & rhs):ptr(rhs.ptr),count(rhs.count){++*rhs.count ;}

T &operator*(){return *ptr}

T* operator->(){return ptr}

SmartPtr &operator=(const SmartPtr & rhs){

if(ptr == rhs.ptr)

return *this ;

if(--*count == 0){

delete ptr ;

delete count ;

}

++*rhs.count ;

count = rhs.count ;

ptr = rhs.ptr ;

}

~SmartPtr(){

if(--*count==0)

delete ptr ;

delete count ;

}

private:

T *ptr ;

int *count ;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  智能指针 弱引用