C++ articles:Guru of the Week #1 (轉)
作者:Hub Sutter
譯者:plpliuly
/*此文是譯者出於自娛翻譯的GotW(Guru of the Week)系列文章第一篇,原文的版權是屬於Hub Sutter(著名的C++專家,《Exceptional C++》的作者)。此文的翻譯沒有徵得原作者的同意,只供學習討論。——譯者
*/
#1 變數的初始化(97年2月21日提出)
難度:4/10
你知道有多少種初始化變數的方法?可千萬要當心那些看起來象變數初始化,而實際上並不是的錯誤喲。
問題:
請看下面的語句,它們之間是否有區別?
SomeType t = u;
SomeType t(u);
SomeType t();
SomeType t;
解決方法:
我們從後往前分別討論上面的四種情況:
SomeType t;
變數t是透過卻省構造SomeType::SomeType()初始化.
SomeType t();
這條語句具有一點“欺騙”性,乍看起來象是一個變數宣告,其實,它是一個函式宣告,這個函式沒有引數,返回一個SomeType型別的返回值。
SomeType t(u);
這是一個直接的初始化。變數t透過建構函式SomeType::SomeType(u)初始化。
SomeType t = u;
這是一個複製初始化,變數t總是透過SomeType的複製建構函式初始化。(儘管這兒有"=",但這只是為了和C語法的相容——這裡只是初始化,而沒有賦值操作,因此運算子=不會被。)
從語義上講:如果變數u為SomeType型別,那麼上述語句就和"SomeType t(u)"或者呼叫SomeType的複製建構函式是等同的;如果u是其他型別的變數,那麼上述語句就和"SomeType t( SomeType(u) )"是等同的——也就是說,u被轉換成一個臨時的SomeType,而t是以該臨時物件複製構造而成。
注意:對於這種情況,具體的常常被允許(但不是必需的)為了而並省去複製構造這一步(也就是將臨時物件的空間直接作為t的記憶體空間——譯者注)。如果是編譯器作了這種最佳化的話,那複製建構函式本身必須仍然是可訪問的。
[忠告]:儘量使用"SomeType t(u)"的形式來初始化變數。它在任何"SomeType t = u"有效的地方使用都是有效的,而且具有其它的優點(比如,它可以帶多個引數)。
(結束)
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-1003249/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- C++ articles:Guru of the Week #4 -- Class Mechantics (轉)C++
- C++ articles:Guru of the Week #3:使用標準庫 (轉)C++
- Guru of the week:#18 迭代指標. (轉)指標
- Guru of the week:#17 型別對映. (轉)型別
- Guru of the week:#19 自動型別轉換. (轉)型別
- Guru of the Week 條款19:自動轉換 (轉)
- Guru of the Week 條款27:轉呼叫函式 (轉)函式
- Guru of the Week 條款28:“Fast Pimpl”技術 (轉)AST
- Guru of The week #20 程式碼的複雜性 Ⅰ. (轉)
- Guru of the Week 條款09:記憶體管理(上篇) (轉)記憶體
- Guru of the Week 條款10:記憶體管理(下篇) (轉)記憶體
- Guru of the Week 條款24:編譯級防火牆 (轉)編譯防火牆
- Guru of the Week 條款30附錄:介面原則 (轉)
- Guru of the Week 條款05:覆寫虛擬函式 (轉)函式
- Guru of the Week 條款13:物件導向程式設計 (轉)物件程式設計
- Guru of the Week #5:虛擬函式的重新定義 (轉)函式
- Guru of the Week 條款07:編譯期的依賴性 (轉)編譯
- Guru of the Week 條款11:物件等同(Object Identity)問題 (轉)物件ObjectIDE
- Guru of the Week 條款14:類之間的關係(上篇) (轉)
- Guru of the Week 條款15:類之間的關係(下篇) (轉)
- Guru of the Week 條款16:具有最大可複用性的通用Containers (轉)AI
- Guru of the Week 條款08:GotW挑戰篇——異常處理的安全性 (轉)Go
- Guru of the Week 條款23:物件的生存期(第二部分) (轉)物件
- Guru of the Week 條款22:物件的生存期(第一部分) (轉)物件
- Guru of the Week 條款21:程式碼的複雜性(第二部分) (轉)
- Guru of the Week 條款20:程式碼的複雜性(第一部分) (轉)
- LeetCode Week 1LeetCode
- week1技術隨筆
- angularJS articles and resourcesAngularJS
- Go 開發者進階週刊(Jan week 1)Go
- 1.week 獨立開發初體驗
- Coursera課程筆記----C++程式設計----Week3筆記C++程式設計
- SAP Retail Differences Between Articles and MaterialsAI
- Standard Functions Used in SAP Retail with ArticlesFunctionAI
- week1讀構建之法-讀書筆記筆記
- Visual C++/MFC指南(1):幕後 (轉)C++
- C++入門解惑(1)——淺析cout (轉)C++
- find the replications and articles from distribution serverServer