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