话不多说直接上代码:
#include<iostream>
using namespace std;
#include<cassert>
template<class T>
class Scopedptr
{
public:
Scopedptr(T* ptr = nullptr) :_ptr(ptr)
{}
T *operator->()
{
return _ptr;
}
T &operator*()
{
return *_ptr;
}
void reset(T *ptr = nullptr)
{
delete _ptr;
_ptr = ptr;
ptr = nullptr;
}
void swap(Scopedptr<T> &sp)
{
swap(_ptr, sp._ptr);
}
~Scopedptr()
{
if (_ptr)
{
delete _ptr;
}
}
private:
Scopedptr(const Scopedptr<T> &sp);//加const是个好习惯
Scopedptr<T>& operator=(const Scopedptr<T> &sp);
T *_ptr;
};
void test()
{
while (1)
{
int *ptr = new int[100*1024*1024];
Scopedptr<int> sp1(ptr);
}
}
int main()
{
test();
system("pause");
}