微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/111352.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐