【牛客带你学编程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:
牛客带你学编程-C++方向:【牛客带你学编程】【C++方向】0基础小白入门培养计划!
查看18道真题和解析