Use Constructor Initializers

C++ Primer 4/e在Constructors這個地方有一個忠告:『In many classes, the distinction between initialization and assignment is strictly a matter of low-level efficiency: A data member is initialized and assigned when it could have been initialized directly. More important than the efficiency issue is the fact that some data members must be initialized.

We must use an initializer for any const or reference member or for any member of a class type that does not have a default constructor.

By routinely using constructor initializers, we can avoid being surprised by compile-time errors when we have a class with a member that requires a constructor initializer.』

中文版的這樣寫:『在很多classes中,初始化和賦值之間的區別僅僅在於效率:成員變數可被初始化,而初始化之後還可以被賦值。比效率重要的則是,某些成員變數一定得被初始化。

注意:對於const類型或reference類型的成員變數,或其class型別沒有default建構式的成員變數,我們必須使用初值器。

如果能夠養成使用建構式初值器的習慣,一旦我們的class有些成員變數需要建構式初值器,就不會大吃一驚地看到編譯期錯誤。』

沒有這個習慣,唉! 🙁

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *