Should every class have a virtual destructor?

2019-01-12 18:30发布

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?

8条回答
神经病院院长
2楼-- · 2019-01-12 18:57

No! Virtual destructors are used only when a object of a derived class is deleted through a base class pointer. If your class is not intended to serve as the base in this scenario, don't make the destructor virtual - you would be sending a wrong message.

查看更多
Luminary・发光体
3楼-- · 2019-01-12 19:03

I would "no" to the general question. Not every class needs one. If you can know that the class should never be inherited from, then there is no need to incur the minor overhead. But if there is a chance, be on the safe side and put one in there.

查看更多
登录 后发表回答