C++核心准则C.121:如果基类被用来定义接口,保证它是一个纯虚类‍

共 1498字,需浏览 3分钟

 ·

2020-01-29 23:23

ba48ffe4d0671ab506d214fc51a319fa.webp

绿色碧玺


C.121: If a base class is used as an interface, make it a pure abstract class

C.121:如果基类被用来定义接口,保证它是一个纯虚类‍






Reason(原因)




A class is more stable (less brittle) if it does not contain data. Interfaces should normally be composed entirely of public pure virtual functions and a default/empty virtual destructor.

不包含数据的类会更稳定(更少脆弱性)。接口通常应该由公开的纯虚函数和默认/空的纯虚析构函数组成。





Example(示例)




class My_interface {
public:
    // ...only pure virtual functions here ...
    virtual ~My_interface() {}   // or =default
};



Example, bad(反面示例)




class Goof {
public:
    // ...only pure virtual functions here ...
    // no virtual destructor
};

class Derived : public Goof {
    string s;
    // ...
};

void use()
{
    unique_ptr p {new Derived{"here we go"}};
    f(p.get()); // use Derived through the Goof interface
    g(p.get()); // use Derived through the Goof interface
} // leak

The Derived is deleted through its Goof interface, so its string is leaked. Give Goof a virtual destructor and all is well.

派生类通过它的Goof接口被销毁,(但是由于Goof的析构函数不是虚函数,导致Derived的析构函数不会被调用,译者注)因此它的string成员会发生泄露。为Goof设计一个虚析构函数就所有都OK了。





Enforcement(实施建议)




  • Warn on any class that contains data members and also has an overridable (non-final) virtual function that wasn't inherited from a base class.

  • 对于所有同时包含数据成员和并非继承自基类的可覆盖(非最终)虚函数的类发出警告。




原文链接:




https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c121-if-a-base-class-is-used-as-an-interface-make-it-a-pure-abstract-class



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

关注【面向对象思考】轻松学习每一天!

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

浏览 48
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报