为了防止程序出现异常,没有及时delete相应的资源,C++出现了auto_ptr类。本程序是一个模拟
智能指针的程序。指针指向一个自定义类型String,使用这个指针类SmartPtr,和平时的指针String*
一样。而它的优势是,程序结束前,不必显示的去调用delete,释放掉分配的内存。在Dev C++环境中,
显示输出的析构测试语句可能不会输出显示,图中显示为VC++ 6.0的结果。
#include
#include
using namespace std;
class String
{
private:
char* str;
public:
String()
{
str=NULL;
}
String(const char* s);
String(const String &sObj);
~String();
String &operator=(const String &sObj);
void show();
};
String::String(const char* s)
{
assert(s!=NULL);
str=new char[strlen(s)+1];
if(str==NULL)
{
cout << "Allocation Failure!" << endl;
exit (1);
}
strcpy(str,s);
}
String::String(const String &sObj)
{
assert(sObj.str!=NULL);
str=new char[strlen(sObj.str)+1];
if(str==NULL)
{
cout << "Allocation Failure!" << endl;
exit (1);
}
strcpy(str,sObj.str);
}
String::~String()
{
cout << "String::destructor..." << endl;
if(str!=NULL)
{
delete []str;
str=NULL;
}
}
String& String::operator=(const String &sObj)
{
if(this == &sObj)
return *this;
delete []str;
str=NULL;
str=new char[strlen(sObj.str)+1];
if(str==NULL)
{
cout << "Allocation Failure!" << endl;
exit (1);
}
strcpy(str,sObj.str);
return *this;
}
void String::show()
{
cout << str << endl;
}
template
class SmartPtr
{
private:
Telem* ptr;
size_t* pRefTimes;
void decRefTimes()
{
(*pRefTimes)--;
if(*pRefTimes==0)
{
delete ptr;
delete pRefTimes;
}
}
public:
SmartPtr(Telem* p=NULL);
~SmartPtr();
SmartPtr(const SmartPtr& sp);
SmartPtr& operator=(const SmartPtr& sp);
Telem* operator->();