在线咨询
QQ咨询
服务热线
服务热线:13125520620
TOP

C++智能指针的简单实现

发布时间:2018-3-21 浏览:3219

template <typename T>
class smart_ptrs {
 
public:
    smart_ptrs(T*); //用普通指针初始化智能指针
    smart_ptrs(smart_ptrs&);
 
    T* operator->(); //自定义指针运算符
    T& operator*(); //自定义解引用运算符
    smart_ptrs& operator=(smart_ptrs&); //自定义赋值运算符
    
    ~smart_ptrs(); //自定义析构函数
 
private:
    int *count; //引用计数
    T *p; //智能指针底层保管的指针
};
跟标准库一样,我们使用模板来实现它。
用普通指针进行初始化时,需要将该指针进行封装,并且引用计数初始化为1。
 
template <typename T>
smart_ptrs<T>::smart_ptrs(T *p): count(new int(1)), p(p) {
}
 
定义拷贝构造函数:
 
template <typename T>
//对普通指针进行拷贝,同时引用计数器加1,因为需要对参数进行修改,所以没有将参数声明为const
smart_ptrs<T>::smart_ptrs(smart_ptrs &sp): count(&(++*sp.count)), p(sp.p)  {
}
定义指针运算符:
 
template <typename T>
 T* smart_ptrs<T>::operator->() {
    return p;
 }
定义解引用运算符,直接返回底层指针的引用:
 
template <typename T>
T& smart_ptrs<T>::operator*() {
    return *p;
}
定义赋值运算符,左边的指针计数减1,右边指针计数加1,当左边指针计数为0时,释放内存:
 
template <typename T>
smart_ptrs<T>& smart_ptrs<T>::operator=(smart_ptrs& sp) {
    ++*sp.count;
    if (--*count == 0) { //自我赋值同样能保持正确
        delete count;
        delete p;
    }
    this->p = sp.p;
    this->count = sp.count;
    return *this;
}
定义析构函数:
 
template <typename T>
smart_ptrs<T>::~smart_ptrs() {
    if (--*count == 0) {
        delete count;
        delete p;
    }
}

软件定制,软件开发,友情提醒。

TAG
软件定制,软件开发,瀚森HANSEN
0
该内容对我有帮助