1. 程式人生 > >C++定製刪除器

C++定製刪除器

上一篇部落格提到的智慧指標採通過引用計數我們能解決多次釋放同一塊記憶體空間的問題,並且和之間直接移交管理權的方式比較這種方式更加靈活安全。但是這種方式也只能處理new出來的空間因為new要和析構中的delete匹配,為了使能和new,malloc,fopen的管理空間匹配,我們需要定製刪除器

#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>
struct Free//建立與malloc匹配的刪除器
{
    void operator()(T* pStr)
    {
        free
(pStr); cout << "Free()" << endl; } }; template<class T> struct Del//建立與new匹配的刪除器 { void operator()(T* pStr) { delete pStr; pStr = NULL; cout << "Del()" << endl; } }; struct Fclose//建立與fopen匹配的刪除器 { void operator()(FILE* pStr) { fclose(pStr); cout
<< "Fclose()" << endl; } }; template<class T, class Delete= Del<T>>第二個引數則是模板類引數 class SharedPtr { public: SharedPtr(T* pStr = NULL, Delete del = Del<T>())//預設使用Del刪除 :_pStr(pStr) ,_pCount(new int(1)) ,_del(del) { } SharedPtr(SharedPtr& sp)//拷貝建構函式
:_pStr(sp._pStr) ,_pCount(sp._pCount) { ++(*_pCount); } SharedPtr<T,Del<T>>& operator=(SharedPtr& sp)//分三種情況 { if (this != &sp&&_pStr != sp._pStr)//判斷是不是自己給自己賦值這種方式更好 { if (_pStr != NULL&&--(*_pCount) == 0) { Del(); } ++(*sp._pCount); _pStr = sp._pStr; _pCount = sp._pCount; } return *this; } int GetCount() { return *_pCount; } void Release() { _del(_pStr); delete _pCount; } ~SharedPtr() { if ( --(*_pCount)== 0) { Release(); } } private: int *_pCount; T* _pStr; Delete _del; }; void FunTest() { /*SharedPtr<int> sp(new int); cout << sp.GetCount() << endl; SharedPtr<int> sp1(sp); cout << sp.GetCount() << endl; SharedPtr<int> sp2(sp); cout << sp.GetCount() << endl; SharedPtr<int> sp3(new int); sp = sp3; cout << sp.GetCount() << endl; cout << sp1.GetCount() << endl;*/ SharedPtr<int>sp(new int); SharedPtr<int,Free<int>>sp1((int*)malloc(sizeof(int)), Free<int>()); } int main() { FunTest(); system("pause"); return 0; }