【牛客带你学编程C++方向】项目练习第3期(参考答案)


参考答案:
#include <iostream>  
using namespace std;  
template <class T> class SmartPointer {  
    unsigned * ref_count;  
    T * ref;  
public:  
    //构造函数, 设定T * ptr的值,并将引用计数设为1  
    SmartPointer(T * ptr) {  
        ref = ptr;  
        ref_count = (unsigned*)malloc( sizeof(unsigned) );  
        *ref_count = 1;  
    }  
    //构造函数,新建一个指向已有对象的智能指针  
    //需要先设定ptr和ref_count  
    //设为指向sptr的ptr和ref_count  
    //并且,因为新建了一个ptr的引用,所以引用计数加一  
    SmartPointer(SmartPointer<T> &sptr) {  
        ref = sptr.ref;  
        ref_count = sptr.ref_count;  
        ++(*ref_count);  
    }  
    //rewrite "="  
    SmartPointer<T> & operator = (SmartPointer<T> &sptr) {  
        if (this == &sptr) return this;  
        if(*ref_count > 0) remove();  
        ref = sptr.ref;  
        ref_count = sptr.ref_count;  
        ++(*ref_count);  
        return *this;  
    }  
    ~SmartPointer() {  
        remove();  
    }  
      
    T getValue() {  
        return *ref;  
    }  
      
protected:  
    void remove() {  
        --(*ref_count);  
        if (*ref_count == 0) {  
            delete ref;  
            free(ref_count);  
            ref = NULL;  
            ref_count = NULL;  
        }  
    }     
};

Tips:
全部评论

相关推荐

axiom15:校友,我感觉你这个简历去华子暑期实习随便去了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务