Destructors實(shí)質(zhì)是釋放資源;
類的析構(gòu)執(zhí)行順序是先構(gòu)造(Constructed)的(成員),最后被Destructors,數(shù)組成員同樣如此,例如:數(shù)組a[0], a[1], ..., a[8], a[9]: 析構(gòu)執(zhí)行順序是a[9], a[8], ..., a[1], a[0]:不能有參數(shù),不能有返回值,不能重載;只能在(對(duì)象關(guān)閉)自動(dòng)調(diào)用,不能顯示調(diào)用析構(gòu)函數(shù)(除非placement new),不可以調(diào)用兩次。
值得注意的是不能顯式調(diào)用析構(gòu)函數(shù),即使局部變量也不行。此時(shí)我們需要這樣處理:
void someCode()
{
{
File f;
...........
}
// f 的析構(gòu)函數(shù)在此處會(huì)被自動(dòng)調(diào)用!
}
如果上述的方案還是不可行,我們可以考慮增加一個(gè)和析構(gòu)函數(shù)等效的成員方法,例如:我們常見File類,就可增加一個(gè)Close()成員方法,但是要記住和析構(gòu)函數(shù)一樣,不能聯(lián)系調(diào)用兩次,我們可以將一個(gè)fileHandle_數(shù)據(jù)成員設(shè)置為 -1,并且在開頭檢查fileHandle_是否已經(jīng)等于-1;
class File {
public:
void close();
~File();
...
private:
int fileHandle_; // fileHandle_ >= 0 if/only-if it's open
};
File::~File()
{
close();
}
void File::close()
{
if (fileHandle_ >= 0) {
...insert code to call the OS to close the file...
fileHandle_ = -1;
}
}
如果一個(gè)對(duì)象是new的,那么在delete中也不能顯示調(diào)用析構(gòu)函數(shù),因?yàn)閐elete做了兩件事,調(diào)用析構(gòu)銷毀對(duì)象和釋放空間。這里的new可不是operator new,后者只是分配空間,并沒調(diào)用構(gòu)造函數(shù)。
placement最明顯的作用就是把對(duì)象放到特定的內(nèi)存位置。
#include <new> // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()
{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2
Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal
...
}
Line #3中的構(gòu)造函數(shù)中的this指針將等于place,f的返回值也是place,注意:placenew指向的指針要有足夠的空間,并且需要為所創(chuàng)建的對(duì)象進(jìn)行邊界調(diào)整,編譯器和系統(tǒng)不會(huì)對(duì)此進(jìn)行任何檢查,另外placenew的析構(gòu)應(yīng)該像如下這樣編寫:
void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
...
f->~Fred(); // Explicitly call the destructor for the placed object
}
在編寫析構(gòu)函數(shù)時(shí),也不能顯正調(diào)用成員的析構(gòu)函數(shù),類的析構(gòu)函數(shù)會(huì)自動(dòng)調(diào)用成員的析構(gòu),按照和它們?cè)陬愔械穆暶鞯捻樞蛳喾吹捻樞虮晃鰳?gòu)。
在派生類的析構(gòu)中,不能顯式調(diào)用基類的析構(gòu)。派生類的析構(gòu)會(huì)自動(dòng)調(diào)用基類的析構(gòu)函數(shù)。在多重繼承的情況下,直接基類以出現(xiàn)在繼承列表中的順序的反序被析構(gòu)。