做者:LogMsegmentfault
本文原載於 https://segmentfault.com/u/logm/articles,不容許轉載~緩存
std::string encryptPassword(const std::string& password) { using namespace std; string encrypted; //bad,過早定義,若是下一句出異常,這個變量其實沒有用到,致使無謂的構造和析構 if (password.length() < MinimumPasswordLength) { throw logic_error("Password is too short"); } ... //加密過程 return encrypted; } std::string encryptPassword(const std::string& password) { using namespace std; if (password.length() < MinimumPasswordLength) { throw logic_error("Password is too short"); } string encrypted; //ok,要用到時再定義 ... //加密過程 return encrypted; }
//循環內的變量怎麼定義? //方法A:定義於循環外 Widget w; for (int i=0; i<n; ++i) { w = ...; ... } //方法B:定義於循環內 for (int i=0; i<n; ++i) { Widget w(...); ... } //方法A:1個構造函數、1個析構函數、n個賦值操做,變量w做用域覆蓋到循環之外 //方法B:n個構造函數、n個析構函數,變量w做用域僅在循環內 //具體使用哪一個視狀況而定。 //我本身想了一個很是小衆的寫法,雖然能夠兼得方法A和方法B的長處,可是代碼可讀性下降 for (int i=0, Widget w; i<n; ++i) { w = ...; ... }
C++的新式轉型:安全
const_cast<...>(...)
。移除對象的常量性。dynamic_cast<...>(...)
。在繼承體系中進行安全的向下轉型,效率低。reinterpret_cast<...>(...)
。低級轉型,結果取決於編譯器,不可移植。static_cast<...>(...)
。強迫執行隱式轉換,相似於C中的舊式轉換。異常安全的函數,即便在發生異常的時候也能保證不泄漏資源不破壞數據結構,能夠分爲三種:數據結構
.h
頭文件中,由於大多數編譯器是在編譯期處理inline函數的。(與template相似,template的聲明和實現也應該放在頭文件中,但這不意味着template就必定是inline)