C++核心准则C.132:不要没有理由就将函数声明为虚函数
共 1088字,需浏览 3分钟
·
2020-02-06 23:23
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(反面示例)
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"根本就不会作为基类使用。
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!