建構函式的一個重要作用是為對象申請資源,相應地,解構函式要負責釋放這些資源。下面理解一下解構函式:
何時調用解構函式:(以下摘自《C++ Prime》Page 412)
撤銷類對象時會自動調用解構函式;變數在超出範圍時會自動撤銷;動態分配的對象只有在指向該隊向的指標被刪除時才撤銷;如果沒有刪除指向動態對象的指標,則不會運行該對象的解構函式,對象會一直存在,從而導致記憶體流失。PS:當對象的引用或者指標超出範圍時,不會運行解構函式。只有刪除指向動態指派至的指標或者實際對象(而不是對象的引用)超出範圍時,才會運行解構函式。
下面對這條規律進行考察:
#include <string.h>#include <vector>#include <iostream>using namespace std;int i=0;int j=0;class CDemo{ public: CDemo():str(NULL){cout<<"constructor_"<<i++<<endl;}; CDemo(const CDemo &cd){cout<<"constructor_"<<i++<<endl;this->str=new char[strlen(cd.str)+1];strcpy(str,cd.str);}; ~CDemo(){cout<<"destrcutor_"<<j++<<endl;if(str) delete []str;}; char *str;};int main(){ CDemo *pDemo=new CDemo(); cout<<"R1"<<endl; { CDemo d1; CDemo &d2=d1; d2.str=new char[32]; strcpy(d2.str,"hello wordl"); } cout<<"R2"<<endl; pDemo->str=new char[32]; strcpy(pDemo->str,"this is pDemo2"); delete pDemo;}
程式輸出結果
constructor_0R1constructor_1destructor_0R2destructor_1
符合上述規律。