C++核心準(zhǔn)則C.132:不要沒(méi)有理由就將函數(shù)聲明為虛函數(shù)?
C.132: Don't make a function?virtual?without reason
C.132:不要沒(méi)有理由就將函數(shù)聲明為虛函數(shù)?
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.
多余的虛函數(shù)會(huì)增加運(yùn)行時(shí)和目標(biāo)碼的大小。虛函數(shù)可以被覆蓋,因此也可以說(shuō)對(duì)派生類對(duì)錯(cuò)誤開放。在模板繼承時(shí),虛函數(shù)一定會(huì)引起代碼重復(fù)。
Example, bad(反面示例)
template
class?Vector?{
public:
????//?...
????virtual?int?size()?const?{?return?sz;?}???//?bad:?what?good?could?a?derived?class?do?
private:
????T*?elem;???//?the?elements
????int?sz;????//?number?of?elements
};
This kind of "vector" isn't meant to be used as a base class at all.
這種類型的"vector"根本就不會(huì)作為基類使用。
Enforcement(實(shí)施建議)
Flag a class with virtual functions but no derived classes.
標(biāo)記出沒(méi)有派生類卻但是卻有虛函數(shù)的類。
Flag a class where all member functions are virtual and have implementations.
標(biāo)記出所有的函數(shù)都是虛函數(shù)卻又包含實(shí)現(xiàn)的類。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c132-dont-make-a-function-virtual-without-reason
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/p>

