c++智能指针实现

来源:互联网 发布:linux dns配置文件详解 编辑:程序博客网 时间:2024/06/05 11:54

c++智能指针实现,使用模板实现智能指针,帮助你管理new出来的内存。

file:share_ptr.h

#include <iostream>

//引用计数类
template<typename T>
struct ref_ptr  
{
ref_ptr(T* obj) :_obj(obj), _refCount(1)

{

};

~ref_ptr()

{
delete _obj;
};
//对象数据
T*  _obj; 
//引用计数
int _refCount;
};

template<typename T>
class share_ptr
{
public:
share_ptr() :_ref(nullptr)
{

};
share_ptr(T* obj) :_ref( new ref_ptr<T>(obj) )
{

};

~share_ptr()
{
//引用计数为0时,删除对象
if (_ref && 0 == --_ref->_refCount)
{
delete _ref;
}
};
//赋值构造函数,引用计数加1
share_ptr(const share_ptr& ptr) :_ref(ptr._ref)
{
if (_ref)
{
++_ref->_refCount;
}
};
//=操作符重载,解除原来对象,引用计数减1,右值对象引用计数加1
share_ptr& operator = (const share_ptr& ptr)
{
if (ptr._ref)
{
++ptr._ref->_refCount;
}
if ( _ref && 0 == --_ref->_refCount)
{
delete _ref;
}
_ref = ptr._ref;
return *this;
};

T* get()
{
return _ref ? _ref->_obj : nullptr;
};
//重置
void reset(T* obj)
{
if (_ref && 0 == --_ref->_refCount)
{
delete _ref;
}
_ref = new ref_ptr<T>(obj);
};

private:
ref_ptr<T>* _ref;

};


test:

#include "share_ptr.h"
using namespace std;

struct Test_Ptr
{
Test_Ptr(int num){
_num = num;
}
int _num;
};

void main()
{
share_ptr<Test_Ptr> shareT;
if (!shareT.get())
{
shareT.reset(new Test_Ptr(100));
}


Test_Ptr* obj = shareT.get();

share_ptr<Test_Ptr> shareT11(shareT);

share_ptr<Test_Ptr> shareT22 = shareT11;

printf("num is %d\n", obj->_num);
}

0 0
原创粉丝点击