日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

virtual析构函数的作用?

發布時間:2023/12/20 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 virtual析构函数的作用? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

***************************************************

更多精彩,歡迎進入:http://shop115376623.taobao.com

***************************************************


大家知道,析構函數是為了在對象不被使用之后釋放它的資源,虛函數是為了實現多態。那么把析構函數聲明為vitual有什么作用呢?請看下面的代碼:

1???????? #include?
2?????? using namespace std;
3
4?????? class Base
5?????? {
6?????? public:
7?????? ???????? Base() {};?????? //Base的構造函數
8?????? ??????? ~Base()??????? //Base的析構函數
9?????? ???????? {
10???? ???????? ???????? cout << "Output from the destructor of class Base!" << endl;
11???? ???????? };
12???? ???????? virtual void DoSomething()?
13???? ???????? {
14???? ???????? ???????? cout << "Do something in class Base!" << endl;
15???? ???????? };
16???? };
17????
18???? class Derived : public Base
19???? {
20???? public:
21???? ???????? Derived() {};? ???//Derived的構造函數
22???? ???????? ~Derived()????? //Derived的析構函數
23???? ???????? {
24???? ???????? ???????? cout << "Output from the destructor of class Derived!" << endl;
25???? ???????? };
26???? ???????? void DoSomething()
27???? ???????? {
28???? ???????? ???????? cout << "Do something in class Derived!" << endl;
29???? ???????? };
30???? };
31????
32???? int main()
33???? {
34???? ???????? Derived *pTest1 = new Derived(); ??//Derived類的指針
35???? ???????? pTest1->DoSomething();
36???? ???????? delete pTest1;
37????
38???? ???????? cout << endl;
39????
40???? ???????? Base *pTest2 = new Derived(); ?????//Base類的指針
41???? ???????? pTest2->DoSomething();
42???? ???????? delete pTest2;
43????
44???? ???????? return 0;
45???? }
先看程序輸出結果:
1?????? Do something in class Derived!
2?????? Output from the destructor of class Derived!
3?????? Output from the destructor of class Base!
4??????
5?????? Do something in class Derived!
6?????? Output from the destructor of class Base!
代碼第36行可以正常釋放pTest1的資源,而代碼第42行沒有正常釋放pTest2的資源,因為從結果看Derived類的析構函數并沒有被調用。通常情況下類的析構函數里面都是釋放內存資源,而析構函數不被調用的話就會造成內存泄漏。原因是指針pTest2是Base類型的指針,釋放pTest2時只進行Base類的析構函數。在代碼第8行前面加上 virtual 關鍵字后的運行結果如下:
1?????? Do something in class Derived!
2?????? Output from the destructor of class Derived!
3?????? Output from the destructor of class Base!
4??????
5?????? Do something in class Derived!
6?????? Output from the destructor of class Derived!
7?????? Output from the destructor of class Base!
此時釋放指針pTest2時,由于Base的析構函數是virtual的,就會先找到并執行Derived類的析構函數,然后再執行Base類的析構函數,資源正常釋放, 避免了內存泄漏
因此, 只有當一個類被用來作為基類的時候,才會把析構函數寫成虛函數

總結

以上是生活随笔為你收集整理的virtual析构函数的作用?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。