C++智能指针原理分析与简单实现

xiaoxiao2021-02-28  107

一个简单智能指针实现的思路如下:

  智能指针,简单来讲是使用引用计数的方法,来跟踪监控指针。当引用计数为0时就delete 所跟踪的目标指针,释放内存   智能指针将一个指针封装到一个类中,当调用智能指针的拷贝构造函数时,将引用计数+1(因为新创建的智能指针也引用了目标指针)   重载智能指针的赋值操作符,等号左边的对象引用计数-1,右边的对象引用计数+1,右边的目标指针和引用计数赋值给左边的对象   智能指针的析构函数将引用计数-1,并判断是否为0,如果是的话delete 目标指针

示例如下(为方便测试,加入了输出打印,已屏蔽):

template <class T> class smart_ptr { private: T* ptr; int* count; public: smart_ptr(T* p=0):ptr(p),count(new int(1))//构造时将引用计数初始化为1 { } smart_ptr(const smart_ptr& src)//拷贝构造时引用计数+1 { ++*src.count; count=src.count; ptr=src.ptr; //cout<<"after copy:count is "<<*count<<endl; } smart_ptr& operator=(const smart_ptr& src)//赋值时左边对象引用计数+1,右边对象引用计数-1 { --*count; if(*count==0)//判断计数是否为0,为0立即释放内存 delete ptr; count=src.count; ++*count; ptr=src.ptr; //if(count)cout<<"after fuzhi:count is"<<*count<<endl; //else cout<<"mem released"<<endl; } T* operator->()//重载指针的箭头操作符 { return ptr; } T& operator*()//重载指针的解引用操作符 { return *ptr; } ~smart_ptr()//析构中引用计数-1,判断计数是否为0,为0才释放内存 { --*count; if(*count==0) { delete ptr; delete count; ptr=NULL; count=NULL; } //if(count)cout<<"destructor:count is"<<*count<<endl; //else cout<<"mem released"<<endl; } };

转载请注明原文地址: https://www.6miu.com/read-39698.html

最新回复(0)