码迷,mamicode.com
首页 > 其他好文 > 详细

为什么需要虚析构函数?

时间:2016-01-05 15:11:50      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

When should my destructor be virtual?

When someone will delete a derived-class object via a base-class pointer.

In particular, here’s when you need to make your destructor virtual:
•if someone will derive from your class,
•and if someone will say new Derived, where Derived is derived from your class,
•and if someone will say delete p, where the actual object’s type is Derived but the pointer p’s type is your class.

Confused? Here’s a simplified rule of thumb that usually protects you and usually doesn’t cost you anything: make your destructor virtual if your class has any virtual functions. Rationale:
•that usually protects you because most base classes have at least one virtual function.
•that usually doesn’t cost you anything because there is no added per-object space-cost for the second or subsequent virtual in your class. In other words, you’ve already paid all the per-object space-cost that you’ll ever pay once you add the first virtual function, so the virtual destructor doesn’t add any additional per-object space cost. (Everything in this bullet is theoretically compiler-specific, but in practice it will be valid on almost all compilers.)

Note: in a derived class, if your base class has a virtual destructor, your own destructor is automatically virtual. You might need an explicitly defined destructor for other reasons, but there’s no need to redeclare a destructor simply to make sure it is virtual. No matter whether you declare it with the virtual keyword, declare it without the virtual keyword, or don’t declare it at all, it’s still virtual.

By the way, if you’re interested, here are the mechanical details of why you need a virtual destructor when someone says delete using a Base pointer that’s pointing at a Derived object. When you say delete p, and the class of p has a virtual destructor, the destructor that gets invoked is the one associated with the type of the object *p, not necessarily the one associated with the type of the pointer. This is A Good Thing. In fact, violating that rule makes your program undefined. The technical term for that is, “Yuck.”

既然继承的目的(特指public继承)是为了被复用,那么一个准备用作基类的类理应有虚函数成员,不然派生类如何被复用呢?

派生类的正确设计思路是:在public接口不变的前提下,只去override那些虚函数成员。只有这样,才能做到“被复用”。

在这种情况下,增加一个虚析构函数不仅不会带来额外的开销,而且是保障正确性的必要条件!

为什么需要虚析构函数?

标签:

原文地址:http://www.cnblogs.com/hustxujinkang/p/5102185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!