为什么不是所有的功能作为虚拟在C + +? [英] Why not have all the functions as virtual in C++?

查看:98
本文介绍了为什么不是所有的功能作为虚拟在C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道虚函数有一个开销去解引用来调用一个方法。但我想现代建筑速度几乎可以忽略不计。

I know that virtual functions have an overhead of dereferencing to call a method. But I guess with modern architectural speed it is almost negligible.


  1. 有没有什么特别的原因,为什么C ++中的所有函数都不是Java中的虚函数?

  2. 从我的知识,在基类中定义一个函数virtual是足够/必要的。现在当我写一个父类,我可能不知道哪些方法会覆盖。这意味着,当写一个子类时,有人必须编辑父类。这听起来不方便,有时不可能?

更新:

Jon Skeet的答案如下:

Update:
Summarizing from Jon Skeet's answer below:

这是一个折衷,明确让别人意识到他们是继承的功能[这本身有潜在的风险[(检查Jon的回应)

It's a trade-off between explicitly making someone realize that they are inheriting functionality [which has potential risks in themselves [(check Jon's response)] [and potential small performance gains] with a trade-off for less flexibility, more code changes, and a steeper learning curve.

虚函数不能内联,因为内联必须在运行时发生。

Virtual functions cannot be in-lined because inlining have to happen at runtime. This have performance impacts when you expect you functions benefits from inlining.

这可能有其他原因,我很想知道和总结他们。

There might be potentially other reasons, and I would love to know and summarize them.

推荐答案

有很多理由控制哪些方法是虚拟的而不是性能。虽然我不会实际上使我的大多数方法在Java中最终,我可能应该...除非一个方法被设计为被重写,它可能不应该虚拟IMO。

There are good reasons for controlling which methods are virtual beyond performance. While I don't actually make most of my methods final in Java, I probably should... unless a method is designed to be overridden, it probably shouldn't be virtual IMO.

设计继承可能是棘手的 - 特别是它意味着你需要记录更多的什么可能称为它和它可能调用。想象一下,如果你有两个虚方法,一个调用另一个 - 必须记录,否则有人可以重写被调用的方法与一个实现调用调用方法,不知不觉地创建一个堆栈溢出(如果有尾调用优化,则为无限循环)。在这一点上,你的实现灵活性会降低 - 你不能在以后的日子切换它。

Designing for inheritance can be tricky - in particular it means you need to document far more about what might call it and what it might call. Imagine if you have two virtual methods, and one calls the other - that must be documented, otherwise someone could override the "called" method with an implementation which calls the "calling" method, unwittingly creating a stack overflow (or infinite loop if there's tail call optimization). At that point you've then got less flexibility in your implementation - you can't switch it round at a later date.

请注意,C#是一个类似Java语言在各种方式,但选择使方法非虚拟默认。一些其他人不喜欢这个,但我肯定欢迎它 - 我实际上更喜欢这些类是默认不可继承的。

Note that C# is a similar language to Java in various ways, but chose to make methods non-virtual by default. Some other people aren't keen on this, but I certainly welcome it - and I'd actually prefer that classes were uninheritable by default too.

基本上,它下来来自Josh Bloch的建议:继承的设计或禁止它。

Basically, it comes down to this advice from Josh Bloch: design for inheritance or prohibit it.

这篇关于为什么不是所有的功能作为虚拟在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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