智能指针(Smart Pointer)

来源:互联网 发布:淘宝店与客人聊天 编辑:程序博客网 时间:2024/05/17 22:39

个智能指针类

比起一般指针,智能指针会自动地管理内存(释放不需要的内存),而不需要程序员去操心。 它能避免野指针(dangling pointers),内存泄漏(memory leaks), 分配失败等情况的发生。智能指针需要为所有实例维护一个引用计数, 这样才能在恰当的时刻(引用计数为0时)将内存释放。

版本一:

#include <iostream>#include <cstdlib>using namespace std;template <typename T>class SmartPointer{protected:  T *ref;unsigned *ref_count;private:void clear(){delete ref;free(ref_count);ref = NULL; // 避免它成为野指针ref_count = NULL;}public:SmartPointer(T* ptr)//构造函数{cout<<"constructor"<<endl;ref = ptr;ref_count = (unsigned*)malloc(sizeof(unsigned));*ref_count = 1;}SmartPointer(SmartPointer<T>& sptr)//复制构造函数{cout<<"copy constructor"<<endl;ref = sptr.ref;ref_count = sptr.ref_count;++*ref_count;}SmartPointer<T>& operator=(SmartPointer<T> &sptr)//赋值构造函数{if (this != &sptr) {if (--*ref_count == 0)//左操作数ref_count减1,右操作数ref_count加1,因为左操作数将被右操作数覆盖{clear();cout<<"operator= clear"<<endl;}ref = sptr.ref;ref_count = sptr.ref_count;++*ref_count;//右操作数+1}return *this;}~SmartPointer(){if (--*ref_count == 0){clear();cout<<"destructor clear"<<endl;}}T getValue() { return *ref; }};int main(){int *ip1 = new int();*ip1 = 1;int *ip2 = new int();*ip2 = 2;SmartPointer<int> sp1(ip1), sp2(ip2); //显式调用构造函数SmartPointer(T* ptr)//隐式调用复制构造函数SmartPointer(SmartPointer<T>& sptr),等价于SmartPointer<int> spa = SmartPointer<int>(sp1);SmartPointer<int> spa = sp1;sp2 = spa;      // 调用赋值构造函数return 0;}


原创粉丝点击