# Item 26: 只要有可能就推遲變量定義
作者:Scott Meyers
譯者:fatalerror99 (iTePub's Nirvana)
發布:http://blog.csdn.net/fatalerror99/
只要你定義了一個帶有構造函數和析構函數的類型的變量,當控制流程到達變量定義的時候會使你擔負構造成本,而當變量離開作用域的時候會使你擔負析構成本。如果有無用變量造成這一成本,你就要盡你所能去避免它。
你可能認為你從來不會定義無用的變量,但是也許你應該再想一想。考慮下面這個函數,只要 password 的長度滿足要求,它就返回一個 password 的加密版本。如果 password 太短,函數就會拋出一個定義在標準 C++ 庫中的 logic_error 類型的異常(參見 Item 54):
```
// this function defines the variable "encrypted" too soon
std::string encryptPassword(const std::string& password)
{
using namespace std;
string encrypted;
if (password.length() < MinimumPasswordLength) {
throw logic_error("Password is too short");
}
... // do whatever is necessary to place an
// encrypted version of password in encrypted
return encrypted;
}
```
對象 encrypted 在這個函數中并不是完全無用,但是如果拋出了一個異常,它就是無用的。換句話說,即使 encryptPassword 拋出一個異常,你也要為構造和析構 encrypted 付出代價。因此得出以下結論:你最好將 encrypted 的定義推遲到你確信你真的需要它的時候:
```
// this function postpones encrypted's definition until it's truly necessary
std::string encryptPassword(const std::string& password)
{
using namespace std;
if (password.length() < MinimumPasswordLength) {
throw logic_error("Password is too short");
}
string encrypted;
... // do whatever is necessary to place an
// encrypted version of password in encrypted
return encrypted;
}
```
這一代碼仍然沒有達到它本可以達到的那樣緊湊,因為定義 encrypted 的時候沒有任何初始化參數。這就意味著很多情況下將使用它的缺省構造函數,對于一個對象你首先應該做的就是給它一些值,這經常可以通過賦值來完成。Item 4 解釋了為什么缺省構造(default-constructing)一個對象然后賦值給它比用你真正需要它持有的值初始化它更低效。那個分析也適用于此。例如,假設 encryptPassword 的核心部分是在這個函數中完成的:
```
void encrypt(std::string& s); // encrypts s in place
```
那么,encryptPassword 就可以這樣實現,即使它還不是最好的方法:
```
// this function postpones encrypted's definition until
// it's necessary, but it's still needlessly inefficient
std::string encryptPassword(const std::string& password)
{
... // check length as above
string encrypted; // default-construct encrypted
encrypted = password; // assign to encrypted
encrypt(encrypted);
return encrypted;
}
```
一個更可取得方法是用 password 初始化 encrypted,從而跳過毫無意義并可能很昂貴的缺省構造:
```
// finally, the best way to define and initialize encrypted
std::string encryptPassword(const std::string& password)
{
... // check length
string encrypted(password); // define and initialize
// via copy constructor
encrypt(encrypted);
return encrypted;
}
```
這個建議就是本 Item 的標題中的“只要有可能(as long as possible)”的真正含義。你不僅應該推遲一個變量的定義直到你不得不用它之前的最后一刻,而且應該試圖推遲它的定義直到你得到了它的初始化參數。通過這樣的做法,你可以避免構造和析構無用對象,而且還可以避免不必要的缺省構造。更進一步,通過在它們的含義已經非常明確的上下文中初始化它們,有助于對變量的作用文檔化。
“但是對于循環會如何?”你可能會有這樣的疑問。如果一個變量僅僅在一個循環內使用,是循環外面定義它并在每次循環迭代時賦值給它更好一些,還是在循環內部定義這個變量更好一些呢?也就是說,下面這兩個大致的結構中哪個更好一些?
```
// Approach A: define outside loop // Approach B: define inside loop
Widget w;
for (int i = 0; i < n; ++i){ for (int i = 0; i < n; ++i) {
w = some value dependent on i; Widget w(some value dependent on i);
... ...
}
```
這里我將一個類型 string 的對象換成了一個類型 Widget 的對象,以避免對這個對象的構造、析構或賦值操作的成本的任何已有的預見。
對于 Widget 的操作而言,就是下面這兩個方法的成本:
* 方法 A:1 個構造函數 + 1 個析構函數 + n 個賦值。
* 方法 B:n 個構造函數 + n 個析構函數。
對于那些賦值的成本低于一個構造函數/析構函數對的成本的類,方法 A 通常更高效。特別是在 n 變得很大的情況下。否則,方法 B 可能更好一些。此外,方法 A 與方法 B 相比,使得名字 w 在一個較大的區域(包含循環的那個區域)內均可見,這可能會破壞程序的易理解性和可維護性。因此得出以下結論:除非你確信以下兩點:(1)賦值比構造函數/析構函數對成本更低,而且(2)你正在涉及你的代碼中的性能敏感的部分,否則,你應該默認使用方法 B。
Things to Remember
* 只要有可能就推遲變量定義。這樣可以增加程序的清晰度并提高程序的性能。
- Preface(前言)
- Introduction(導言)
- Terminology(術語)
- Item 1: 將 C++ 視為 federation of languages(語言聯合體)
- Item 2: 用 consts, enums 和 inlines 取代 #defines
- Item 3: 只要可能就用 const
- Item 4: 確保 objects(對象)在使用前被初始化
- Item 5: 了解 C++ 為你偷偷地加上和調用了什么函數
- Item 6: 如果你不想使用 compiler-generated functions(編譯器生成函數),就明確拒絕
- Item 7: 在 polymorphic base classes(多態基類)中將 destructors(析構函數)聲明為 virtual(虛擬)
- Item 8: 防止因為 exceptions(異常)而離開 destructors(析構函數)
- Item 9: 絕不要在 construction(構造)或 destruction(析構)期間調用 virtual functions(虛擬函數)
- Item 10: 讓 assignment operators(賦值運算符)返回一個 reference to *this(引向 *this 的引用)
- Item 11: 在 operator= 中處理 assignment to self(自賦值)
- Item 12: 拷貝一個對象的所有組成部分
- Item 13: 使用對象管理資源
- Item 14: 謹慎考慮資源管理類的拷貝行為
- Item 15: 在資源管理類中準備訪問裸資源(raw resources)
- Item 16: 使用相同形式的 new 和 delete
- Item 17: 在一個獨立的語句中將 new 出來的對象存入智能指針
- Item 18: 使接口易于正確使用,而難以錯誤使用
- Item 19: 視類設計為類型設計
- Item 20: 用 pass-by-reference-to-const(傳引用給 const)取代 pass-by-value(傳值)
- Item 21: 當你必須返回一個對象時不要試圖返回一個引用
- Item 22: 將數據成員聲明為 private
- Item 23: 用非成員非友元函數取代成員函數
- Item 24: 當類型轉換應該用于所有參數時,聲明為非成員函數
- Item 25: 考慮支持不拋異常的 swap
- Item 26: 只要有可能就推遲變量定義
- Item 27: 將強制轉型減到最少
- Item 28: 避免返回對象內部構件的“句柄”
- Item 29: 爭取異常安全(exception-safe)的代碼
- Item 30: 理解 inline 化的介入和排除
- Item 31: 最小化文件之間的編譯依賴
- Item 32: 確保 public inheritance 模擬 "is-a"
- Item 33: 避免覆蓋(hiding)“通過繼承得到的名字”
- Item 34: 區分 inheritance of interface(接口繼承)和 inheritance of implementation(實現繼承)
- Item 35: 考慮可選的 virtual functions(虛擬函數)的替代方法
- Item 36: 絕不要重定義一個 inherited non-virtual function(通過繼承得到的非虛擬函數)
- Item 37: 絕不要重定義一個函數的 inherited default parameter value(通過繼承得到的缺省參數值)
- Item 38: 通過 composition(復合)模擬 "has-a"(有一個)或 "is-implemented-in-terms-of"(是根據……實現的)
- Item 39: 謹慎使用 private inheritance(私有繼承)
- Item 40: 謹慎使用 multiple inheritance(多繼承)
- Item 41: 理解 implicit interfaces(隱式接口)和 compile-time polymorphism(編譯期多態)
- Item 42: 理解 typename 的兩個含義
- Item 43: 了解如何訪問 templatized base classes(模板化基類)中的名字
- Item 44: 從 templates(模板)中分離出 parameter-independent(參數無關)的代碼
- Item 45: 用 member function templates(成員函數模板) 接受 "all compatible types"(“所有兼容類型”)
- Item 46: 需要 type conversions(類型轉換)時在 templates(模板)內定義 non-member functions(非成員函數)
- Item 47: 為類型信息使用 traits classes(特征類)
- Item 48: 感受 template metaprogramming(模板元編程)
- Item 49: 了解 new-handler 的行為
- Item 50: 領會何時替換 new 和 delete 才有意義
- Item 51: 編寫 new 和 delete 時要遵守慣例
- Item 52: 如果編寫了 placement new,就要編寫 placement delete
- 附錄 A. 超越 Effective C++
- 附錄 B. 第二和第三版之間的 Item 映射