PHP虛析構(gòu)函數(shù)怎么用-創(chuàng)新互聯(lián)

這篇文章主要講解了“PHP虛析構(gòu)函數(shù)怎么用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“PHP虛析構(gòu)函數(shù)怎么用”吧!

目前成都創(chuàng)新互聯(lián)公司已為數(shù)千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、網(wǎng)站托管運營、企業(yè)網(wǎng)站設(shè)計、遂川網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
預(yù)備知識

用一個例子來說明虛析函數(shù)的必要性.在程序清單1中,基類A的構(gòu)造函數(shù)動態(tài)分配5個字節(jié),其析構(gòu)函數(shù)負(fù)責(zé)釋放這塊內(nèi)存.派生類Z的構(gòu)造函數(shù)動態(tài)分配5000個字節(jié),其析構(gòu)函數(shù)負(fù)責(zé)釋放這塊內(nèi)存.

程序清單1
#include <iostream>
using namespace std;

class A{ // base class
	public:
		A(){
			 cout<<"A() firing"<<endl;
			 p = new char[5]; // allocate 5 bytes
			
		}
		~A(){
			cout<<"~A() firing"<<endl;
			delete[] p;// free 5 bytes
		}
	
	private:
		char *p;
};

class Z: public A {//derived class
	public:
		Z(){
			cout<<"Z() firing"<<endl;
			q = new char[5000];//allocate 5000 bytes
		}			
		~Z(){
			cout<<"~Z() firing"<<endl;
			delete[] q; //free 50000 bytes
		}
	
	 private:
			char *q;
};

void f();


int main(){
	for(unsigned i =0; i<3; i++)
		f();
	return 0;
}

void f(){
	A *ptr; //pointer to base class
	ptr = new Z(); // pointer to derived class object
	delete ptr; //~A() fires but not ~z()
}//***** Caution:50000 bytes of inaccessible storage

在main中三次調(diào)用f函數(shù):

void f(){
	A *ptr; //pointer to base class
	ptr = new Z(); // pointer to derived class object
	delete ptr; //~A() fires but not ~z()
}//***** Caution:50000 bytes of inaccessible storage

由于類A和Z的構(gòu)造函數(shù)與析構(gòu)函數(shù)輸出了跟蹤信息,程序運行的結(jié)果如圖所示:

將析構(gòu)函數(shù)聲明為虛成員函數(shù)可以解決程序清單1中的問題:

class A{ // base class
	public:
		A(){
			 cout<<"A() firing"<<endl;
			 p = new char[5]; // allocate 5 bytes
			
		}
		virtual ~A(){
			cout<<"~A() firing"<<endl;
			delete[] p;// free 5 bytes
		}
	
	private:
		char *p;
};
.......

通過定義基類的析構(gòu)函數(shù)~A()為虛成員函數(shù),可以確保其派生類的析構(gòu)函數(shù)也為虛成員函數(shù).為了使代碼更清晰,我們可以明確地使用關(guān)鍵字virtual來聲明~Z(),不過即使我們不這樣做,~Z()仍然為虛成員函數(shù),修改后的程序輸出如下圖所示:

現(xiàn)在,由于析構(gòu)函數(shù)已經(jīng)聲明為虛成員函數(shù),當(dāng)通過ptr來刪除其所指針的對象時,編譯器進(jìn)行的是運行期綁定.在這里,因為ptr指向一個Z類型的對象,所以~Z()被調(diào)用.我們看到隨后~A()也被調(diào)用了,這是通過將析構(gòu)函數(shù)定義為虛成員函數(shù),我們就保證了在調(diào)用f時不會產(chǎn)生內(nèi)存遺漏.

感謝各位的閱讀,以上就是“PHP虛析構(gòu)函數(shù)怎么用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對PHP虛析構(gòu)函數(shù)怎么用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

當(dāng)前題目:PHP虛析構(gòu)函數(shù)怎么用-創(chuàng)新互聯(lián)
URL鏈接:http://muchs.cn/article12/ddcodc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、微信小程序、軟件開發(fā)標(biāo)簽優(yōu)化、網(wǎng)站策劃小程序開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)