CCI_chapter 13C++

13.9Write a smart pointer (smart_ptr) class

template<class T>class SmartPoint{
 public:
    SmartPoint(T *ref){
        ref_ = ref;
        count_ = (unsigned int *)malloc(sizeof(unsigned int ));
        *count_ = 1;
    }
    SmartPoint(SmartPoint<T> &sptr){
        ref_ = sptr.ref_;
        count_ = sptr.count_;
        ++(*count_);
    }
    SmartPoint<T>& operator =(SmartPoint<T> &sptr)
    {  
        if(this != sptr){
            ref_ = sptr.ref_;
            count_ = sptr.count_;
            ++(*count_);
        }
        return *this;
    }
    ~SmartPoint()
    {
        --(*count_);
        if(*count_ == 0)
         {
            delete ref_;
            free(count_);
            ref_ = NULL;
            count_ = NULL;
         }
         
    }
    T getValue(){
        rturn *ref_;
    }
 private:
    T* ref_;
    unsigned int *count_;
};

  

posted @   冰点猎手  阅读(222)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示