最终类的使用案例

编程入门 行业动态 更新时间:2024-10-28 08:18:34
本文介绍了最终类的使用案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读关于草本的意见 Sutter的Guru of the Week简化了 virtual 函数,最后看到他提到这个:

I was reading comments on Herb Sutter's Guru of the Week redux about virtual functions, and finally saw him mentioning this:

[...]最终的用法是稀有的 - 好吧,他们是。我不知道很多,在标准化期间,Bjarne反复询问它解决的问题的例子和应该使用的模式,我不记得任何突出的主要。我知道的唯一的一个是,如果你定义一个库模块(这不是一个标准的概念),然后使叶类final可以给编译器更多的信息虚拟化调用,因为知道的库外的代码, t进一步推导,但我不知道这些天是如此重要的是整个程序优化,包括积极的虚拟化。

[...] "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. The only one I know of offhand is that if you’re defining a library module (which isn’t a Standard concept yet) then making leaf classes final can give the compiler more information to devirtualize calls because of knowing code outside the library won’t further derive, but I’m not sure how important that is these days in the presence of whole program optimization including aggressive devirtualization.

这个答案没有提供许多关于类的 final 用例的例子,我有兴趣知道它真正可以解决什么问题。你知道吗,或者在课程上最终只会变成一些晦涩的和几乎没有使用的功能?

That answer does not provide many examples about the use cases for final on classes, and I would be interested in knowing what problems it can really solve. Do you know any, or will final on classes only become some obscure and almost unused feature?

推荐答案

一个有趣的异常用例,我发现我描述了这里。简而言之,通过阻止类似int类的继承,你可以在将来的版本库中使用内置类型替换它,而不会破坏你的用户代码。

One interesting unusual use case I have found I described here. In short, by preventing inheritance from your int-like class, you buy yourself a possibility to replace it with a built-in type in the future releases of your library, without the risk of breaking your user's code.

但更常见的例子是虚拟化。如果将类标记为final,编译器可以应用某些运行时优化。例如,

But a more common example is devirtualization. If you mark your class as final, compiler can apply certain run-time optimizations. For instance,

struct Object { virtual void run() = 0; virtual ~Object() {} }; struct Impl final : Object { void run() override {} }; void fun(Impl & i) { i.run(); // inlined! }

调用 i.run code>现在可以内联,因为 final 说明符。编译器知道不需要vtable查找。

The call to i.run() can be now inlined due to final specifier. The compiler knows that vtable look-up will not be needed.

更多推荐

最终类的使用案例

本文发布于:2023-11-25 07:39:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:案例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!