template<class T>
struct Del
{
void operator()(const T* ptr)
{
cout << "Del" <<ptr<< endl;
delete ptr;
}
};
template<class T>
struct FFF
{
void operator()(const T* ptr)
{
cout << "delete[]" << endl;
delete[] ptr;
}
};
struct Free//仿函数
{
void operator() (void* ptr)
{
cout << "free:" << ptr << endl;
free(ptr);
}
};
struct Fclose
{
void operator() (void* ptr)
{
cout << "fclose:" << ptr << endl;
fclose((FILE*)ptr);
}
};
template<class T,class Deleter =Del<T> >
class Shared_ptr
{
public:
Shared_ptr(T *ptr) :_ptr(ptr), _refcount(new long(1))
{}
Shared_ptr(T *ptr, Deleter del) :_ptr(ptr), _refcount(new long(1)), _del(del)
{}
~Shared_ptr()
{
Realease();
}
protected:
void Realease()
{
if (--*_refcount == 0)
{
_del(_ptr);
delete _refcount;
}
}
private:
T *_ptr;
Deleter _del;
long *_refcount;
};
void test1()
{
Shared_ptr<int> s1(new int(10));
//return 0;
Shared_ptr<int, Free>s2((int*)malloc(sizeof(int)* 10), Free());
// Shared_ptr<int, Free>s2((int*)malloc(sizeof(int)* 10), Free());
Shared_ptr<FILE, Fclose>s3(fopen("test.txt","w"), Fclose());
}
int main()
{
test1();
}原文地址:http://10955910.blog.51cto.com/10945910/1754449