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<Goof> 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.
- 对于所有同时包含数据成员和并非继承自基类的可覆盖(非最终)虚函数的类发出警告。
 原文链接:
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
 
 
                     
            
        













 
                    

 
                 
                    