析构函数前加virtual关键字的作用?
来源:互联网 发布:多益网络上市了吗 编辑:程序博客网 时间:2024/06/06 10:07
大家知道,析构函数是为了在对象不被使用之后释放它的资源,虚函数是为了实现多态。那么把析构函数声明为vitual有什么作用呢?请看下面的代码:
先看程序输出结果:
代码第36行可以正常释放pTest1的资源,而代码第42行没有正常释放pTest2的资源,因为从结果看Derived类的析构函数并没有被调用。通常情况下类的析构函数里面都是释放内存资源,而析构函数不被调用的话就会造成内存泄漏。原因是指针pTest2是Base类型的指针,释放pTest2时只进行Base类的析构函数。在代码第8行前面加上virtual关键字后的运行结果如下:
此时释放指针pTest2时,由于Base的析构函数是virtual的,就会先找到并执行Derived类的析构函数,然后再执行Base类的析构函数,资源正常释放,避免了内存泄漏。
因此,只有当一个类被用来作为基类的时候,才会把析构函数写成虚函数。
#include<iostream>using namespace std;class Base{public:Base() {}; //Base的构造函数~Base() //Base的析构函数{cout << "Output from the destructor of class Base!" << endl;};virtual void DoSomething(){cout << "Do something in class Base!" << endl;};};class Derived : public Base{public:Derived() {}; //Derived的构造函数~Derived() //Derived的析构函数{cout << "Output from the destructor of class Derived!" << endl;};void DoSomething(){cout << "Do something in class Derived!" << endl;};};int main(){Derived *pTest1 = new Derived(); //Derived类的指针pTest1->DoSomething();delete pTest1;cout << endl;Base *pTest2 = new Derived(); //Base类的指针pTest2->DoSomething();delete pTest2;return 0;}
先看程序输出结果:
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类的析构函数,资源正常释放,避免了内存泄漏。
因此,只有当一个类被用来作为基类的时候,才会把析构函数写成虚函数。
0 0
- 析构函数前加virtual关键字的作用?
- virtual关键字的作用
- virtual析构函数的作用?
- virtual析构函数的作用?
- virtual析构函数的作用
- virtual析构函数的作用?
- 析构函数 private 、virtual的作用
- 析构函数 private 、virtual的作用
- virtual 析构函数的作用
- virtual析构函数的作用?
- 析构函数 private 、virtual的作用
- 基函数的析构函数要加virtual
- virtual 析构函数作用
- php中在函数前加static的作用
- php中函数前加&符号的作用
- 【C++基础 08】virtual析构函数的作用
- virtual析构函数(作用)
- virtual虚函数的作用
- iOS 获取磁盘,获取文件大小
- 【那些年遇到过的面试题】switch case default
- Android实训案例(六)——四大组件之一BroadcastReceiver的基本使用,拨号,短信,SD卡,开机,应用安装卸载监听
- 组件化的Web王国
- 设备控制器
- 析构函数前加virtual关键字的作用?
- Oracle修改字段类型方法总结
- 网狐客户端调试
- OpenBR之一:Windows下配置OpenBR
- a
- binbinyyang---接着上一篇文章 说锁屏上显示Activity
- Neither the JAVA_HOME nor the JRE_HOME environment variable is defined解决方案
- 《剑指offer》用两个栈实现队列
- 《剑指offer》:[51]数组中的重复数字