C++核心準(zhǔn)則E4,5:設(shè)計并構(gòu)建不變量

E.4: Design your error-handling strategy around invariants
E.4:圍繞不變量設(shè)計錯誤處理策略
Reason(原因)
To use an object it must be in a valid state (defined formally or informally by an invariant) and to recover from an error every object not destroyed must be in a valid state.
為了使用對象,它一定要處于有效狀態(tài)(通過不變量形式化或非形式化定義)并且為了從錯誤中恢復(fù),所有沒有銷毀的對象必須處于有效狀態(tài)。
Note(注意)
An?invariant?is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.
不變量是一個適用于對象成員的邏輯條件,這個條件必須有構(gòu)造函數(shù)建立,可以作為公有成員函數(shù)的前提條件。
Enforcement(實施建議)
???

E.5: Let a constructor establish an invariant, and throw if it cannot
E.5:讓構(gòu)造函數(shù)建立不變量,如果不能就拋異常
Reason(原因)
Leaving an object without its invariant established is asking for trouble. Not all member functions can be called.
建立一個對象卻沒有建立不變量是在找麻煩。不是所有成員函數(shù)都是可以被調(diào)用的。
Example(示例)
class Vector { // very simplified vector of doubles// if elem != nullptr then elem points to sz doublespublic:Vector() : elem{nullptr}, sz{0}{}Vector(int s) : elem{new double[s]}, sz{s} { /* initialize elements */ }~Vector() { delete [] elem; }double& operator[](int s) { return elem[s]; }// ...private:ownerelem; int sz;};
The class invariant - here stated as a comment - is established by the constructors.?new?throws if it cannot allocate the required memory. The operators, notably the subscript operator, relies on the invariant.
See also:?If a constructor cannot construct a valid object, throw an exception
類不變量-這里通過注釋聲明-通過構(gòu)造函數(shù)建立了。如果不能分配要求的內(nèi)存,new操作會拋出異常。運算符,特別是下標(biāo)運算符依靠不變量。參見:如果不能構(gòu)建有效的對象,就拋出異常。
Enforcement(實施建議)
Flag classes with?private?state without a constructor (public, protected, or private).
標(biāo)記那些沒有構(gòu)造函數(shù)(公有的,私有的或保護的)卻有私有成員的類。
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e4-design-your-error-handling-strategy-around-invariants
新書介紹
以下是本人3月份出版的新書,拜托多多關(guān)注!

本書利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設(shè)計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設(shè)計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設(shè)計模式的利弊,并合理運用設(shè)計模式。
對設(shè)計模式感興趣而且希望隨學(xué)隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書中的示例作為設(shè)計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
