C++核心准则C.132:不要没有理由就将函数声明为虚函数


C++核心准则C.132:不要没有理由就将函数声明为虚函数

岫玉

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


觉得本文有帮助?请分享给更多人。

更多精彩文章欢迎关注关注【面向对象思考】!

面向对象开发,面向对象思考!


分享到:


相關文章: