C++多态为什么要定义虚析构函数
来源:互联网 发布:外国人来中国旅游数据 编辑:程序博客网 时间:2024/06/06 02:00
请看父类Base类没有定义虚析构函数的例子:
#include <iostream>class Base{public:virtual int start(){std::cout<<"Base::start"<<std::endl;}~Base(){std::cout<<"Base::~Base() "<<std::endl;}};class Derived : public Base{public: virtualint start(){m_pInt = new int [10];std::cout<<"Derived::start()"<<std::endl;}~Derived(){std::cout<<"Derived::~Derived()"<<std::endl;if(NULL != m_pInt){delete m_pInt;m_pInt = NULL;}}private:int *m_pInt;};int main(){Base *pBase = new Derived();pBase->start();delete pBase;pBase = NULL;return 0;}
执行结果
对不起,使用基类指向派生类,释放类对象时,没有执行到Derived类的析构函数,使得Derived类申请有堆内存或者申请有资源的情况,会造成内存泄漏或资源泄漏。
解决方法: 基类的析构函数定义为虚析构函数,这样的使用基类指向派生类,删除基类指针时,能执行到Derived类的析构函数。
#include <iostream>class Base{public:virtual int start(){std::cout<<"Base::start"<<std::endl;}virtual ~Base(){std::cout<<"Base::~Base() "<<std::endl;}};class Derived : public Base{public: virtualint start(){m_pInt = new int [10];std::cout<<"Derived::start()"<<std::endl;}virtual ~Derived(){std::cout<<"Derived::~Derived()"<<std::endl;if(NULL != m_pInt){delete m_pInt;m_pInt = NULL;}}private:int *m_pInt;};int main(){Base *pBase = new Derived();pBase->start();delete pBase;pBase = NULL;return 0;}
阅读全文
0 0
- C++多态为什么要定义虚析构函数
- 为什么要定义成虚析构函数
- 为什么析构函数要定义为虚函数
- C++析构函数为什么要定义成虚函数
- 析构函数为什么要定义成虚析构函数?
- 看到这个你能明白很多为什么要定义new,为什么函数不要定义
- C++:为什么inline函数的定义要放在头文件里 + inline和宏定义的区别(暂未体会到)
- C++(多态实现原理)函数重写,重载,重定义
- JAVA里面main函数为什么要定义为static的?
- java中的main函数为什么要定义为static的?
- 为什么要将成员函数的声明和定义分开
- 为什么大数组要定义在main函数外
- c++ 中为什么要定义public protect…
- 为什么要将析构函数定义为虚函数
- [C++] 基类一定要定义虚析构函数
- C中为什么要用内联函数
- 为什么要定义interface
- 为什么要定义接口?
- 机器学习实战-树回归
- Android 自定义View之绘制折线图、曲线图
- java线程池讲解
- React-Native集成到已有项目过程及问题处理
- egret.eui皮肤与组件(2)
- C++多态为什么要定义虚析构函数
- 开通了博客,立个Flag
- JSP学习笔记(2)_JSP各种元素(1)
- 可变参数
- 1050. String Subtraction 解析
- bzoj2906 颜色 分块
- HFOI2017.7.13校内赛(普及组)题解
- MATLAB基本语法
- 原型模式