確定對象被使用前巳先被初始化

 

通常如果你使用C part of C++  而且初始化可能招致運行期成本,
那麼就不保證發生初始化。一旦進入non-C part ofC ,規則有些變化。這就很好
地解釋了爲什麼array (來自C part of C++ )不保證其內容被初始化,而vector (來
自STLpart ofC++) 卻有此保證。

 

 

表面上這似乎是個無法決定的狀態,而最佳處理辦法就是:永遠在使用對象之
前先將它初始化。對於無任何成員的內置類型,你必須手工完成此事。例z如
int x = 0;
const char* text = "A C-style string";
double d;

 std::cin » d; //以讀取input  的方式完成初始化
至於內置類型以外的任何其他東西,初始化責任落在構造函數( constructors)
身上。規則很簡單:確保每一個構造函數都將對象的每一個成員初始化。

 

 

 

這個規則很容易奉行,重要的是別混淆了賦值 和初始化
( initialization) 。考慮一個用來表現通訊簿的class ,其構造函數如下:
class PhoneNumber { ... };
class ABEntry { IIABEntry =嘰Address Book Entry"
public:
ABEntry(const std::string& name, const std::string& address ,
const std::list<PhoneNumber>& phones);
private:
std::string theName;
std::string theAddress;
std::list<PhoneNumber> thePhones;
int numTimesConsulted;
ABEntry: :ABEntry(const std: :string& n缸ne , const std: : string& address,
const std::list<PhoneNumber>& phones)
theName 二口arne; //這些都是賦值(assignments) ,
theAddress = address; //始化(initializations)。
thePhones = phones;
numTimesConsulted = 0;

 

這會導致ABEntry 對象帶有你期望(你指定)的值,但不是最佳做法。C++ 規
,對象的成員變量的初始化動作發生在進入構造函數本體之前。在ABEntry 構造
函數內, theNarr吼theAddress 和thePhones 都不是被初始化,而是被賦值。初始
化的發生時間更早,發生於這些成員的default 構造函數被自動調用之時(比進入
ABEntry 構造函數本體的時間更早)。但這對numTimesConsu1ted 不爲真,因爲它
屬於內置類型,不保證一定在你所看到的那個賦值動作的時間點之前獲得初值。

 

ABEntry 構造函數的一個較佳寫法是,使用所謂的member initialization list (成
員初值列〉替換賦值動作:
ABEntry: :ABEntry(const std: :string& n缸ne , const std: :string& address,
const std::1ist<PhoneNumber>& phones)
:theNarne(narne) ,
theAddress(address) , //現在,這些都是初始化(initializations )
thePhones(phones) ,
numTimesConsu1ted(O)
( } //現在,構造函數本體不必有任何動作

 

這個構造函數和上一個的最終結果相同,但通常效率較高。基於賦值的那個版
本(本例第一版本)首先調用default 構造函數爲theNarne, theAddress 和thePhones
設初值,然後立刻再對它們賦予新值。default 構造函數的一切作爲因此浪費了。成
員初值列(member initialization list) 的做法(本例第二版本)避免了這一問題,因
爲初值列中針對各個成員變量而設的實參,被拿去作爲各成員變量之構造函數的實
參。本例中的theNarne 以name爲初值進行copy構造, theAddress 以address 爲
初值進行copy構造, thePhones 以phones 爲初值進行copy構造。

 

規則:
規定總是在初值列中列出所有成員變量,以免還得記住哪些成員變量(如果它們在
初值列中被遺漏的話〉可以無需初值。


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章