随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-04-25 20:07

题目:为什么基类的析构函数必须声明为虚函数?

解法:不是必须,而是应该,这是种规范。对于基类中执行的一些动态资源分配,如果基类的析构函数不是虚函数,那么 派生类的析构函数在自动调用的时候,不会调用基类的析构函数,这样就会造成资源未释放引起的内存泄漏。

代码:

复制代码
 1 // 13.6 If a class is defined as base class, why must its destructor be declared "virtual"?
 2 // Answer:
 3 //    If the destructor of base class is declared "virtual", it will be called when a derived class object is being destroyed.
 4 //    Otherwise it wouldn't. As base class may already have some allocated data or other resources, the destructor of basic class must be called to clear them up.
 5 //    Missing the base class destructor will leave out those data allocated for base class, causing memory leakage.
 6 //    Even though there're no dynamically allocated data, the base class should be declared "virtual", as a good practice of coding.
 7 class A {
 8 public:
 9     virtual ~A() {};
10 };
11 
12 class B: public A {
13 public:
14     ~B() {};
15 };
16 
17 int main()
18 {
19     A *ptr = new B();
20     delete ptr;
21     // Here ~B() will be called first, ~A() to follow.
22     return 0;
23 }
复制代码

 

 posted on   zhuli19901106  阅读(179)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示