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

efcc7f84186571447d6dba1fc1f3ff16.png

岫玉

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

templateclass 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


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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值