c++ - 最终类的用例

标签 c++ inheritance c++11 gotw

我正在阅读 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/

相关文章:

c++ - bitbake grpc 交叉编译/配置失败,出现错误 c-ares::cares 引用文件/usr/lib/libcares.so.2.2.0

c++ - 来自 c 的随机十六进制答案

c++ - 使用 lambda 函数定义非常小的辅助函数是一种好的风格吗?

c++ - 是否有按值传递类对象的标准程序?

c++ - 如何删除位图中的像素?

c++ - 如何在 C++ 中处理大数据元素?

java - 通过父类(super class)引用变量访问子类成员

java - JButton 中的组合与继承

C++ 运算符重载和继承

c++ - 从 std::function 继承构造函数时为 "function returning a function"