C.132: Don't make a function virtual without reason
C.132:不要沒有理由就將函數聲明為虛函數
Reason(原因)
Redundant virtual increases run-time and object-code size. A virtual function can be overridden and is thus open to mistakes in a derived class. A virtual function ensures code replication in a templated hierarchy.
多餘的虛函數會增加運行時和目標碼的大小。虛函數可以被覆蓋,也可以說對派生類對錯誤開放。在模板繼承時,虛函數一定會引起代碼重複。
Example, bad(反面示例)
<code>template<classt>classVector{public://...virtualintsize()const{returnsz;}//bad:whatgoodcouldaderivedclassdo?private:T*elem;//theelementsintsz;//numberofelements};/<classt>/<code>
This kind of "vector" isn't meant to be used as a base class at all.
這種類型的"vector"根本就不會作為基類使用。
Enforcement(實施建議)
- Flag a class with virtual functions but no derived classes.
- 標記出沒有派生類卻但是卻有虛函數的類。
- Flag a class where all member functions are virtual and have implementations.
- 標記出所有的函數都是虛函數卻又包含實現的類。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c132-dont-make-a-function-virtual-without-reason
覺得本文有幫助?請分享給更多人。
更多精彩文章歡迎關注關注【面向對象思考】!
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章