我正在阅读 comments在 Herb Sutter 的 Guru of the Week redux 上关于 virtual
函数,最后看到他提到这个:
[...] “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
用例的示例,我很想知道它可以真正解决哪些问题。你知道吗,或者类上的 final
只会成为一些晦涩且几乎未使用的功能?
最佳答案
我发现我描述了一个有趣的不寻常用例 here .简而言之,通过防止从类 int 类继承,您可以在将来的库版本中将其替换为内置类型,而不会破坏用户代码。
但更常见的例子是去虚拟化。如果将类标记为最终类,编译器可以应用某些运行时优化。例如,
struct Object {
virtual void run() = 0;
virtual ~Object() {}
};
struct Impl final : Object
{
void run() override {}
};
void fun(Impl & i)
{
i.run(); // inlined!
}
由于 final
说明符,现在可以内联对 i.run()
的调用。编译器知道不需要 vtable 查找。
关于c++ - 最终类的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16808184/