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

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

概述关闭选民,请帮助我改进问题,以便重新开放: 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. 根据该指南,如果您有一 关闭选民,请帮助我改进问题,以便重新开放: 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 – 具有公共非虚拟析构函数的类是否应标记为“最终”?全部内容,希望文章能够帮你解决c – 具有公共非虚拟析构函数的类是否应标记为“最终”?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1255765.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存