每个类都有一个虚拟析构函数? [英] Should every class have a virtual destructor?

查看:153
本文介绍了每个类都有一个虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java和C#支持不能作为基类使用 final 密封关键字。在C ++中,但是没有好的方法来防止一个类被派生出来,从而使类的作者有一个困境,每个类都有一个虚拟析构函数或者不是?






编辑:由于C ++ 11这不再是真的,你可以指定一个类 final






一方面给一个对象一个虚拟析构函数意味着它将有一个 vtable ,因此消耗4(或64位机器上的8)附加字节对于 vptr 的每个对象。



另一方面,如果有人以后从这个类派生,类通过指向基类的指针,程序将被定义不清(由于没有虚拟析构函数),坦率地优化每个对象的指针是可笑的。



握手上有一个虚拟析构函数



有些人认为你需要明确的理由不使用虚拟析构函数(因为这个问题)和其他人说,你应该使用它们,只有当你有理由相信你的类是从派生的, 问题是,你想执行规则吗?如果一个类没有一个虚拟析构函数,任何使用该类的人都知道它不是从中派生的,如果你尝试它有什么限制。这不够好吗?



或者你需要编译器,如果任何人执行你没有做的事情时抛出一个硬错误预期?



如果你打算让人们从中得到一个虚拟析构函数。否则不要,并假设任何使用您的代码的智能足以正确使用您的代码。


Java and C# support the notion of classes that can't be used as base classes with the final and sealed keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?


Edit: Since C++11 this is no longer true, you can specify that a class is final.


On the one hand giving an object a virtual destructor means it will have a vtable and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the vptr.

On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous.

On the gripping hand having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically.

Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of this question) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do you think?

解决方案

The question is really, do you want to enforce rules about how your classes should be used? Why? If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough?

Or do you need the compiler to throw a hard error if anyone dares to do something you hadn't anticipated?

Give the class a virtual destructor if you intend for people to derive from it. Otherwise don't, and assume that anyone using your code is intelligent enough to use your code correctly.

这篇关于每个类都有一个虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆