C.41: A constructor should create a fully initialized object C.41构造函数生成的对象应该被完全初始化
Reason(原因)
A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
构造函数有责任为类建立不变式。类的用户应该可以假设构造出的对象式可用的。
Example, bad(反面示例)
class X1 {
FILE* f; // call init() before any other function
// ...
public:
X1() {}
void init(); // initialize f
void read(); // read from f
// ...
};
void f()
{
X1 file;
file.read(); // crash or bad read!
// ...
file.init(); // too late
// ...
}
Compilers do not read comments.
编译器不会读注释。
Exception(例外)
If a valid object cannot conveniently be constructed by a constructor, use a factory function.
如果不能方便地通过构造函数构建合法的对象,使用一个工厂函数。
Enforcement(实施建议)
Note(注意)
If a constructor acquires a resource (to create a valid object), that resource should be released by the destructor. The idiom of having constructors acquire resources and destructors release them is called RAII ("Resource Acquisition Is Initialization").
如果构造函数请求了资源(为了生成合法的对象),那个资源应该被析构函数释放。构造函数申请资源然后析构函数释放它们的做法被称为RAII("资源申请即初始化")。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c40-define-a-constructor-if-a-class-has-an-invariant
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!