本文共 1480 字,大约阅读时间需要 4 分钟。
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_ptrp {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
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
转载地址:https://oothinking.blog.csdn.net/article/details/105078042 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!