SharePtr的简单实现
#include <iostream>
#include<string>
using namespace std;
#pragma warning(disable:4996)
template<class T, class Del>
class SharePtr
{
public:
SharePtr(T* ptr) //构造函数
:_ptr(ptr), _ref(new int(1))
{
cout << "SharePtr(T* ptr) " << endl;
}
SharePtr(SharePtr& cp)//拷贝构造函数
{
cout << "SharePtr(SharePtr& cp)" << endl;
_ptr = cp._ptr;
_ref = cp._ref;
(*_ref)++;
}
~SharePtr()//析构函数
{
Release();
}
void Release()
{
if (--(*_ref) == 0)
{
delete _ref;
_del(_ptr);
}
}
T* operator->()//->操作符重载
{
return _ptr;
}
T& operator*()//解引用操作符重载
{
return *_ptr;
}
SharePtr& operator=(SharePtr& sp)//赋值操作符重载
{
if (_ptr != sp._ptr)
{
Release();
_ptr = sp._ptr;
_ref = sp._ref;
(*_ref)++;
}
return *this;
}
private:
T* _ptr;
int* _ref;
Del _del;//这是一个对象函数决定着析构时以什么方式释放申请的空间
};
//以上为class SharePtr的内容
template<class T>
struct Delete
{
void operator()(T* ptr)
{
cout << "delete" << endl;
delete ptr;
}
};
template<class T>
struct DeleteArr
{
void operator()(T* ptr)
{
cout << "delete[]" << endl;
delete[] ptr;
}
};
template<class T>
struct Free
{
void operator()(T* ptr)
{
cout << "free" << endl;
free(ptr);
}
};
template<class T>
struct Close
{
void operator()(T* ptr)
{
cout << "close" << endl;
if (ptr != NULL)
{
fclose(ptr);
}
}
};
//以上为对象函数
//下面为主函数代码
int main()
{
SharePtr<int, Delete<int>> p1(new int(10));
SharePtr<int, Delete<int>> p2(p1);
SharePtr<string, DeleteArr<string>> p3(new string[3]);
SharePtr<string, DeleteArr<string>> p4(p3);
SharePtr<string, DeleteArr<string>> p5(p4);
SharePtr<int, Delete<int>> p6(new int(20));
SharePtr<int, Free<int>> p7 = (int*)malloc(sizeof(int));
SharePtr<FILE, Close<FILE>> p8 = fopen("FILENAME", "r");
cout << *p1 << "," << *p2 << endl;
p2 = p6;
*p1 = 15;
cout << *p1 << "," << *p2 << endl;
return 0;
}
结果为