加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:26:35 所属栏目:百科 来源:网络整理
导读:关闭选民,请帮助我改进问题,以便重新开放: 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是多范式的,开始实施仅适合用例子集的窄方法是没有意义的.从我所知道的,你的建议基本上归结为禁止人们使用继承,除非他们也将使用动态多态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读