C++核心准则C.41:构造函数生成的对象应该被完全初始化
共 1621字,需浏览 4分钟
·
2019-12-27 23:22
C.41构造函数生成的对象应该被完全初始化
A constructor establishes the invariant for a class. A user of a class should be able to assume that a constructed object is usable.
构造函数有责任为类建立不变式。类的用户应该可以假设构造出的对象式可用的。
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.
编译器不会读注释。
If a valid object cannot conveniently be constructed by a constructor, use a factory function.
如果不能方便地通过构造函数构建合法的对象,使用一个工厂函数。
(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协议,尽量确认是否包含了所有的前置条件。
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!