为什么对 virtual 关键字如此模糊?
在阅读一个或另一个 boost 库的文档时,我遇到了一些语句,暗示 virtual
关键字是一种邪恶的东西。请参阅http://www.boost.org/ doc/libs/1_46_1/libs/msm/doc/HTML/ch03s05.html,例如:
不会说 MSM 强迫你接受虚拟关键字!
根据 http://www.parashift.com/c++ -faq-lite/virtual-functions.html#faq-20.4,virtual关键字确实没有那么糟糕,我对它的感觉也是一样的。
为什么一些 boost 人认为虚拟函数调用是有史以来最糟糕的事情?我的印象是,boost 的人确实是 C++ 方面的专家,所以一定有一些东西。
When reading the documentation of one or another boost library, I encountered some statements giving a hint that the virtual
keyword is kind of evil. See http://www.boost.org/doc/libs/1_46_1/libs/msm/doc/HTML/ch03s05.html, for example:
It will not be said that MSM forces the virtual keyword down your throat!
According to http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.4, the virtual keyword is really not that bad, and my feeling about it is the same.
Why do some of the boost people regard virtual function calls as the worst thing ever? I have the impression that the boost guys are really the experts on C++, so there must be something about it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
存在静态多态性优于动态多态性的情况。这就是克里斯托夫在这里所说的。而已。
there is case where static polymorphism is preferred to dynamic one. That's what Christophe states here. Nothing more.
运行时多态性有一个额外的成本,即vtable。一旦 vtable 添加到类型中,就无法将其删除。 C++ 的核心优势之一是“您只需为您使用的内容付费”。因此,为了使对象尽可能精简,一些库尽可能避免虚拟函数。不是因为它是邪恶的,而是因为你可能不想要它。
Runtime polymorphism has an extra cost, namely the vtable. Once the vtable is added in a type, it can't be removed. One of the core strengths of C++ is that "you only pay for what you use". Therefore, to keep objects as lean as possible, several libraries avoid virtual functions when possible. Not because it is evil, but because you may not want it.
我认为推论是 MSM 不会通过其内部工作原理或结构强迫您将自己的代码成员声明为虚拟成员,或覆盖他们的成员。有些库需要这样做,例如动态创建类的“代理”的库,例如模拟或惰性加载器。
I think the inference is that MSM does not, through its inner workings or structure, force you to declare members of your own code as virtual, or to override theirs. There are libraries that require this, for instance libraries that dynamically create "proxies" of your classes such as mocks or lazy-loaders.