为什么默认情况下析构函数不是虚拟的[C ++] [英] Why are destructors not virtual by default [C++]

查看:87
本文介绍了为什么默认情况下析构函数不是虚拟的[C ++]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有至少一个其他虚函数的类,C ++为什么不默认将析构函数虚拟化为?在这种情况下,添加虚拟析构函数不会花费我任何钱,而没有一个是(几乎吗? )总是一个错误. C ++ 0x会解决这个问题吗?

Why doesn't C++ make destructors virtual by default for classes that have at least one other virtual function? In this case adding a virtual destructor costs me nothing, and not having one is (almost?) always a bug. Will C++0x address this?

推荐答案

您不需要为不需要的东西付费.如果您从不通过基指针删除,则可能不需要间接的析构函数调用的开销.

You don't pay for what you don't need. If you never delete through base pointer, you may not want the overhead of the indirected destructor call.

也许您认为vtable的存在是唯一的开销.但是也必须考虑每个函数的分派,如果我想直接进行析构函数调用分派,则应该允许我这样做.

Perhaps you were thinking that the mere existence of the vtable is the only overhead. But each individual function dispatch has to be considered, too, and if I want to make my destructor call dispatch directly, I should be allowed to do so.

如果您确实删除了基本指针并且该类具有虚方法,那么编译器将警告您,这很好.

It would be nice of your compiler to warn you if you do ever delete a base pointer and that class has virtual methods, I suppose.

让我在这里提出Simon的出色评论:查看

Let me pull Simon's excellent comment in here: Check out this SO question on the code generated for destructors. As you can see, there's also code-bloat overhead to be considered.

这篇关于为什么默认情况下析构函数不是虚拟的[C ++]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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