先来看一段代码:




1. //test.cpp  
2. #include <iostream>
3. using namespace std;
4.
5. class father
6. {
7. public:
8. father()
9. {
10. new int;
11. }
12.
13. ~father()
14. {
15. delete mPtr;
16. "father Destruction......" << endl;
17. }
18.
19. private:
20. int *mPtr;
21. };
22.
23.
24. class son:public father
25. {
26. public:
27. son()
28. {
29. new long;
30. }
31.
32. ~son()
33. {
34. delete mStr;
35. "son Destruction......" << endl;
36. }
37.
38. private:
39. long *mStr;
40. };
41.
42.
43. int main()
44. {
45. new son;
46. delete p;
47. return 0;
48. }


 

程序运行截图:


C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数_父类

 

从程序的运行结果来看,程序最后只释放了父类的内存,子类的内存并没有释放。则这段程序产生了内存泄露。那是什么原因导致的呢?

main函数中new出来的是子类son的对象,采用一个父类father的指针来接收,故在析构的时候,编译器因为只知道这个指针是父类的,所以只将父类部分的内存析构了,而不会去析构子类的内存,就造成了内存泄露,那么如何避免这种情况的产生呢?

将父类的析构函数改为虚函数,就可以避免这种情况。



    1. //test.cpp  
    2. #include <iostream>
    3. using namespace std;
    4.
    5. class father
    6. {
    7. public:
    8. father()
    9. {
    10. new int;
    11. }
    12.
    13. virtual~father()
    14. {
    15. delete mPtr;
    16. "father Destruction......" << endl;
    17. }
    18.
    19. private:
    20. int *mPtr;
    21. };
    22.
    23.
    24. class son:public father
    25. {
    26. public:
    27. son()
    28. {
    29. new long;
    30. }
    31.
    32. ~son()
    33. {
    34. delete mStr;
    35. "son Destruction......" << endl;
    36. }
    37.
    38. private:
    39. long *mStr;
    40. };
    41.
    42.
    43. int main()
    44. {
    45. new son;
    46. delete p;
    47. return 0;
    48. }



     

    程序运行截图:

     

    C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数_子类_02

    从程序的运行结果可以看出,父类和子类的内存都被析构了。所以在使用多态时一定要将父类的析构函数定义成虚函数,从而避免内存泄露。