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(实施建议)
-
(Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
(简单)所有的构造函数应该初始化所有的成员变量(无论是明确地通过委托构造函数,还是默认构造)
-
(Unknown) If a constructor has an Ensures contract, try to see if it holds as a postcondition.
(不明)如果构造函数包含Ensures协议,尽量确认是否包含了所有的前置条件。
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
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】