C++核心准则C.139:谨慎使用final
发布日期:2021-07-01 05:27:09 浏览次数:2 分类:技术文章

本文共 2126 字,大约阅读时间需要 7 分钟。

C.139: Use final sparingly

C.139:谨慎使用final

 

Reason(原因)

Capping a hierarchy with final is rarely needed for logical reasons and can be damaging to the extensibility of a hierarchy.

很少会因为逻辑方面的原因而使用final关键词关闭后续的覆盖函数,这种做法会破坏继承的扩展性。

 

Example, bad(反面示例)

class Widget { /* ... */ };// nobody will ever want to improve My_widget (or so you thought)class My_widget final : public Widget { /* ... */ };class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that

 

Note(注意)

Not every class is meant to be a base class. Most standard-library classes are examples of that (e.g., std::vector and std::string are not designed to be derived from). This rule is about using final on classes with virtual functions meant to be interfaces for a class hierarchy.

不是所有的类都被设计为基类。大多数标准库中的类就是这方面的例子(例如std::vector和std::string就不是设计用来继承的)。这条规则的使用范围是那些包含虚函数并且意图作为接口被继承的类。

 

Note(注意)

Capping an individual virtual function with final is error-prone as final can easily be overlooked when defining/overriding a set of functions. Fortunately, the compiler catches such mistakes: You cannot re-declare/re-open a final member in a derived class.

定义/覆盖一组函数时,finial很容易被忽略,这种使用final为每个单独的虚函数关闭覆盖函数的做法容易引发错误。幸运的是,编译器可以捕捉这些错误:你无法在派生类中重新定义或重新打开一个final成员。

 

Note(注意)

Claims of performance improvements from final should be substantiated. Too often, such claims are based on conjecture or experience with other languages.

使用final可以提高性能这个判断是缺乏证据的。有太多的情况,这个判断只是源于猜测或者其他语言的经验。

There are examples where final can be important for both logical and performance reasons. One example is a performance-critical AST hierarchy in a compiler or language analysis tool. New derived classes are not added every year and only by library implementers. However, misuses are (or at least have been) far more common.

存在某些场景,无论是由于逻辑还是性能方面的原因,final变得很重要。一个例子就是性能要求非常严格的编译器或者语言分析工具。只有库的实现者会添加新的派生类,而且不会每年增加。但是错误地使用却更加普遍(至少曾经被误用过)。

 

AST:Abstract syntax tree(抽象语法树)-译者注

 

Enforcement(实施建议)

Flag uses of final.

标志对于final的使用。

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c139-use-final-sparingly

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

转载地址:https://oothinking.blog.csdn.net/article/details/105457963 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++核心准则C.140:不要为虚函数和它的覆盖函数设定不同的默认参数
下一篇:使用Eclipse构建树莓派远程调试环境

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月17日 18时39分43秒