温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++使用final时需要注意什么

发布时间:2021-08-24 09:38:46 来源:亿速云 阅读:155 作者:chen 栏目:大数据

这篇文章主要讲解了“C++使用final时需要注意什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++使用final时需要注意什么”吧!

谨慎使用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的使用。

感谢各位的阅读,以上就是“C++使用final时需要注意什么”的内容了,经过本文的学习后,相信大家对C++使用final时需要注意什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI