最终类的使用案例 [英] Use cases for final classes

查看:178
本文介绍了最终类的使用案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于草本的意见 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.

这篇关于最终类的使用案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆