条款25 :尽可能延后变量定义式的出现时间
只要你定義了一個變量,而類型帶有一個構造函數和一個析構函數,你就得忍受構造成本與析構成本。或許你認為你不可能定義一個不會使用的變量,但是請看下面的代碼:
std::stringencryptPassword(conststd::string&password){
??? usingnamespacestd;
??? stringencrypted;
??? if(password.length()<MinimumPasswordLength){
?????????? throwlogic_error("password is short");
??? }
??? ...
??? returnencrypted;
}
對象encrypted并非完全沒有被使用,但是當拋出異常時,這個對象確實沒有被使用,但是你仍舊要忍受起encrypted對象的構造,析構成本。最好的方法是延后encrypted對象的定義式,直到確實需要它時。
std::stringencryptPassword(conststd::string&password){
??? usingnamespacestd;
??? if(password.length()<MinimumPasswordLength){
?????????? throwlogic_error("password is short");
??? }
??? stringencrypted; //延后encrypted對象的定義式
??? ...
??? returnencrypted;
}
假設encryptPassword函數最艱難的部分在以下這個函數中進行:
voidencrypt(std::string&s);
?????? 則我們的encryptPassword函數可以這樣實現:
std::stringencryptPassword(conststd::string&password){
??? usingnamespacestd;
??? ...// 檢查length,如前
??? stringencrypted;
??? encrypted=password;
??? encrypt(encrypted)????
??? returnencrypted;
}
?????? 我們還可以接著去改進:我們知道上例中的encrypted是先定義,并調用了默認的構造函數,再用password進行賦值。這樣,效率是比較低的,我們完全可以直接初始化。
?????? std::stringencryptPassword(conststd::string&password){
?????? usingnamespacestd;
?????? ...//
?????? stringencrypted(password);???
?????? encrypt(encrypted)????
?????? returnencrypted;
}
?
在這里我們再次討論“盡可能延后”的真正意義。你不只應該延后變量的定義,直到非得使用該變量前一刻為止,而是應該嘗試延后這份定義直到能夠給它初值實參為止。
轉載于:https://www.cnblogs.com/loveyakamoz/archive/2012/11/15/2772415.html
總結
以上是生活随笔為你收集整理的条款25 :尽可能延后变量定义式的出现时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美观实用的标签切换菜单
- 下一篇: sql中where和on的区别