c – 具有公共非虚拟析构函数的类是否应标记为“最终”?

关闭选民,请帮助我改进问题,以便重新开放: How can I improve this question so that it gets reopened?

Herb Sutter wrote

A base class destructor should be either public and virtual,or
protected and nonvirtual.

根据该指南,如果您有一个具有公共非虚拟析构函数的类,则该类不应该用作基类.
为什么不把它标记为最终执行?

但萨特也在wrote以下,暗示最终不需要使用:

Re “uses of final are rarer” – well,they sort of are. I don’t kNow
of many,and during standardization Bjarne repeatedly asked for
examples of problems it solved and patterns where it should be used,
and I don’t recall any major ones that stood out.

一个相关的引用,暗示现在应该使用的最终版本来自Scott Meyer的Effective C,第7项:

If you’re ever tempted to inherit from a standard container or any
other class with a non-virtual destructor,resist the temptation!
(Unfortunately,C++ offers no derivation-prevention mechanism akin to
Java’s final classes or C#’s sealed classes.)

一个数据点是standard library has no types marked “final”,但其原因似乎是为了避免破坏代码.

这里有一个类似的问题,但不完全重复,因为它错过了“受保护的非虚拟”选项:Default to making classes either `final` or give them a virtual destructor?

解决方法

According to that guideline,if you have a class with a public non-virtual destructor,then that class shouldn’t be used as a base class. Why not mark it final to enforce that?

因为它是适合某些情况的指南,但不是全部,所以为什么要“强制”它呢?

通过虚函数调用的动态多态性尚未配置,但这是非常好和不允许的继承,但这不是我们使用继承的唯一场景.

C是多范式的,开始实施仅适合用例子集的窄方法是没有意义的.从我所知道的,你的建议基本上归结为禁止人们使用继承,除非他们也将使用动态多态.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...