C++核心準(zhǔn)則C.41:構(gòu)造函數(shù)生成的對(duì)象應(yīng)該被完全初始化

C.41: A constructor should create a fully initialized objectC.41構(gòu)造函數(shù)生成的對(duì)象應(yīng)該被完全初始化

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.
構(gòu)造函數(shù)有責(zé)任為類(lèi)建立不變式。類(lèi)的用戶應(yīng)該可以假設(shè)構(gòu)造出的對(duì)象式可用的。
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.
編譯器不會(huì)讀注釋。
Exception(例外)
If a valid object cannot conveniently be constructed by a constructor, use a factory function.
如果不能方便地通過(guò)構(gòu)造函數(shù)構(gòu)建合法的對(duì)象,使用一個(gè)工廠函數(shù)。
Enforcement(實(shí)施建議)
(Simple) Every constructor should initialize every member variable (either explicitly, via a delegating ctor call or via default construction).
(簡(jiǎn)單)所有的構(gòu)造函數(shù)應(yīng)該初始化所有的成員變量(無(wú)論是明確地通過(guò)委托構(gòu)造函數(shù),還是默認(rèn)構(gòu)造)
(Unknown) If a constructor has an Ensures contract, try to see if it holds as a postcondition.
(不明)如果構(gòu)造函數(shù)包含Ensures協(xié)議,盡量確認(rèn)是否包含了所有的前置條件。
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").
如果構(gòu)造函數(shù)請(qǐng)求了資源(為了生成合法的對(duì)象),那個(gè)資源應(yīng)該被析構(gòu)函數(shù)釋放。構(gòu)造函數(shù)申請(qǐng)資源然后析構(gòu)函數(shù)釋放它們的做法被稱為RAII("資源申請(qǐng)即初始化")。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c40-define-a-constructor-if-a-class-has-an-invariant
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
