【C++】编写一个智能指针类。

来源:互联网 发布:public cms官网 编辑:程序博客网 时间:2024/06/05 20:22

编写一个智能指针类。

智能指针是一个数据类型,一般用模板实现,模拟指针行为的同时还提供自动垃圾回收机制。

它会自动记录SmartPointer<T*>对象的引用计数,一旦T类型对象的引用计数为0,就释放该对象。

除了指针对象外,我们还需要一个引用计数的指针

设定对象的值,并将引用计数计为1,需要一个构造函数

新增对象还需要一个构造函数

析构函数负责引用计数减少和释放内存

通过覆写赋值运算符,才能将一个旧的智能指针赋值给另一个指针,同时旧的引用计数减1,新的引用计数加1

<span style="font-family:Microsoft YaHei;">#include <iostream>using namespace std;template <class T> class SmartPointer {unsigned * ref_count;T * ref;public://构造函数, 设定T * ptr的值,并将引用计数设为1SmartPointer(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;}}};</span>


0 0
原创粉丝点击