Discussion: Define and initialize member variables in the order of member declaration
討論:按照成員聲明的順序定義和初始化成員變量git
Member variables are always initialized in the order they are declared in the class definition, so write them in that order in the constructor initialization list. Writing them in a different order just makes the code confusing because it won't run in the order you see, and that can make it hard to see order-dependent bugs.github
成員變量老是按照它們在類定義中聲明的順序進行初始化,所以請按該順序將其寫入構造函數初始化列表中。以不一樣的順序編寫它們只會使代碼使人困惑,由於它不會按照您看到的順序運行,而且這使得很難看到與順序相關的錯誤。web
class Employee {
string email, first, last;
public:
Employee(const char* firstName, const char* lastName);
// ...
};
Employee::Employee(const char* firstName, const char* lastName)
: first(firstName),
last(lastName),
// BAD: first and last not yet constructed
email(first + "." + last + "@acme.com")
{}
In this example, email will be constructed before first and last because it is declared first. That means its constructor will attempt to use first and last too soon -- not just before they are set to the desired values, but before they are constructed at all.編程
在此示例中,因爲email對象首先被聲明,因此將在first和last以前進行構造。這意味着它的構造函數試圖過早使用first和last-不只早於將它們設置爲所需值以前,甚至會遭遇對象徹底構造以前。設計模式
If the class definition and the constructor body are in separate files, the long-distance influence that the order of member variable declarations has over the constructor's correctness will be even harder to spot.微信
若是類定義和構造函數體位於不一樣的文件中,則成員變量聲明的順序對構造函數正確性的遠程影響將更加難以發現。架構
References(參考):app
[Cline99] §22.03-11, [Dewhurst03] §52-53, [Koenig97] §4, [Lakos96] §10.3.5, [Meyers97] §13, [Murray93] §2.1.3, [Sutter00] §47ide
原文連接函數
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-define-and-initialize-member-variables-in-the-order-of-member-declaration
新書介紹
《實戰Python設計模式》是做者最近出版的新書,拜託多多關注!
本書利用Python 的標準GUI 工具包tkinter,經過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可使讀者瞭解真實的軟件開發工做中每一個設計模式的運用場景和想要解決的問題;另外一方面經過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,併合理運用設計模式。
對設計模式感興趣並且但願隨學隨用的讀者經過本書能夠快速跨越從理解到運用的門檻;但願學習Python GUI 編程的讀者能夠將本書中的示例做爲設計和開發的參考;使用Python 語言進行圖像分析、數據處理工做的讀者能夠直接以本書中的示例爲基礎,迅速構建本身的系統架構。
以爲本文有幫助?請分享給更多人。
關注微信公衆號【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
本文分享自微信公衆號 - 面向對象思考(OOThinkingDalian)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。