virtual 析构函数
来源:互联网 发布:php入门视频教程下载 编辑:程序博客网 时间:2024/06/08 06:26
有时候我们需要用基类的指针删除其子类的对象,这时候要非常注意,倘若基类的析构函数是 non-virtual析构函数,那么事实上,只有基类的析构函数被调用,派生类的析构函数并没有被调用,这可能会导致资源泄漏。为避免这中情况发生,我们可以将基类的析构函数声明为virtual,这样的话,子类对象才能被完全销毁.
- #include <iostream>
- #include <stdlib.h>
- #include <crtdbg.h>
- #ifdef _DEBUG
- #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
- #endif
- using namespace std;
- class BaseClass
- {
- public:
- virtual ~BaseClass() = 0;
- //~BaseClass();
- };
- BaseClass::~BaseClass()
- {
- cout << "the ~BaseClass is called" << endl;
- }
- class DerivedClass : public BaseClass
- {
- public:
- DerivedClass(int x, int y)
- :X(x)
- ,Y(y)
- {
- a = new int[y];
- }
- ~DerivedClass()
- {
- cout << "the ~Derivedclass is called" << endl;
- if(a)
- {
- delete a;
- a = NULL;
- }
- }
- private:
- int X;
- int Y;
- int *a;
- };
- void main()
- {
- //memory check
- _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
- BaseClass *bs= new DerivedClass(2, 3);
- delete bs;
- system("pause");
- }
程序运行结果为
the ~Derivedclass is called
the ~BaseClass is called
基类和派生类的析构函数都被调用
倘若基类的析构函数为~BaseClass();即 non-virtual 析构函数,
程序运行结果为
the ~BaseClass is called,
只有基类的析构函数被调用,子类中指针 a 指向的内存并没有被释放
Dumping objects ->
e:\work\test\test\test.cpp(287) : {128} normal block at 0x00395E38, 12 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
12 字节的内存泄漏了
- virtual 析构函数
- Virtual 析构函数
- virtual 析构函数
- virtual+析构函数
- virtual析构函数
- virtual析构函数
- virtual析构函数
- C++ virtual 析构函数
- C++ virtual 析构函数
- C++ virtual 析构函数
- C++ virtual 析构函数
- C++ virtual 析构函数
- 讨论virtual析构函数
- virtual 析构函数作用
- pure virtual析构函数
- 构造函数,析构函数与virtual
- 析构函数virtual与非virtual区别
- 析构函数virtual和非virtual的区别
- 操作系统组成
- 完全卸载SQL2000
- .net lock的使用方法
- Windows RC版、RTM版、OEM版、RTL版、VOL版的区别
- UVa 10023 - Square root
- virtual 析构函数
- oracle libary cache 命中率
- MFC从屏幕右下角升起的弹窗 .
- TSC条形码打印
- 扩展Django:实现自己的manage命令
- hdu 1176
- hdu 1312 Red and Black
- RHEL 5 安装Oracle10g的一些总结
- 第一课 struts2工作原理