有什么理由不使成员函数虚拟化吗? [英] Is there any reason not to make a member function virtual?

查看:57
本文介绍了有什么理由不使成员函数虚拟化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有真正的理由使成员函数在C ++中虚拟化?当然,总是有性能方面的争论,但这在大多数情况下似乎并不成立,因为虚拟函数的开销相当低.

Is there any real reason not to make a member function virtual in C++? Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.

另一方面,我被遗忘了几次却忘记了将一个虚拟的函数设为 是虚拟的.与性能相比,这似乎是一个更大的争论.因此,有什么理由不使成员函数默认为虚拟吗?

On the other hand, I've been bitten a couple of times with forgetting to make a function virtual that should be virtual. And that seems to be a bigger argument than the performance one. So is there any reason not to make member functions virtual by default?

推荐答案

一种阅读问​​题的方法是:为什么C ++不会默认使每个函数都是虚拟的,除非程序员重写该默认值."无需查阅我的"C ++的设计和演化"副本:除非每个成员函数都为非虚拟函数,否则这将为每个类增加额外的存储空间.在我看来,这将需要在编译器实现上付出更多的努力,并通过为痴迷的性能提供饲料来减慢C ++的采用(我认为自己属于该组.)

One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default." Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual. Seems to me this would have required more effort in the compiler implementation, and slowed down the adoption of C++ by providing fodder to the performance obsessed (I count myself in that group.)

阅读问题的另一种方式是:为什么C ++程序员除非有充分的理由不将每个函数虚拟化,否则为什么?性能的借口可能是原因.取决于您的应用程序和域,这可能是一个很好的理由.例如,我团队的一部分在市场数据行情收录器工厂中工作.在单个流上以100,000+消息/秒的速度,虚拟功能开销将是不可接受的.我团队的其他部分都在复杂的交易基础架构中工作.在这种情况下,将大多数功能虚拟化可能是个好主意,因为额外的灵活性胜过微优化.

Another way to read your questions is "Why do C++ programmers do not make every function virtual unless they have very good reasons not to?" The performance excuse is probably the reason. Depending on your application and domain, this might be a good reason or not. For example, part of my team works in market data ticker plants. At 100,000+ messages/second on a single stream, the virtual function overhead would be unacceptable. Other parts of my team work in complex trading infrastructure. Making most functions virtual is probably a good idea in that context, as the extra flexibility beats the micro-optimization.

这篇关于有什么理由不使成员函数虚拟化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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