*** auto_ptr指针应用(注意auto_ptr已经被弃用)
#include <iostream> #include <memory> #include <string.h> using namespace std; class Test { public: Test():name(NULL){} Test(const char * x) { if (x != NULL) { name = new char [strlen(x)+1]; strcpy(name, x); } } ~Test() { if (name != NULL) { delete [] name; name = NULL; } cout << "Delete name" << endl; } Test & operator = (const char * str) { if (name != NULL) { delete [] name; } name = new char [strlen(str)+1]; strcpy (name, str); return *this; } void ShowName (void) { cout << name << endl; } public: char * name; }; int main() { auto_ptr<Test> TestPtr(new Test("Jason")); //Test * TestPtr = new Test("Jason"); TestPtr->ShowName(); *TestPtr = "Becky"; TestPtr->ShowName(); int y = 1; int x = 0; y = y / x; cout << "End of program!" << endl; return 0; }
运行后屏幕输出为:说明出现异常后auto_ptr指向的对象的析构函数仍然被执行了。
Jason Becky End of program! Delete name
如果把上面代码中注释掉的代码打开,如下:
int main() { //auto_ptr<Test> TestPtr(new Test("Jason")); Test * TestPtr = new Test("Jason"); TestPtr->ShowName(); *TestPtr = "Becky"; TestPtr->ShowName(); int y = 1; int x = 0; y = y / x; cout << "End of program!" << endl; return 0; }
执行后屏幕显示如下:因为没有运用auto_ptr而用的裸指针,可以看到析构函数没有被调用
Jason
Becky
End of program!