最好不要使用final關閉後續的覆蓋函數

最好不要使用final關閉後續的覆蓋函數

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(反面示例)
<code>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/<code>

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就不是設計用來繼承的)。這條規則的使用範圍是那些包含虛函數並且意圖作為接口被繼承的類。


最好不要使用final關閉後續的覆蓋函數

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


覺得本文有幫助?請分享給更多人。

面向對象開發,面向對象思考!


分享到:


相關文章: