僅當須要時再給變量定義

From Effective C++ Item26函數

給定以下的程序:spa

 std::string encryptPassword(const std::string &password)
 {
    using namespace std;
   string encrypted;
   if(password.length() < MinimunPasswordLength)
    {
      throw logic_error("Password is too short!");
    } 
   ...          //do what you want

   return encrypted;
 }

對象encrypted在此函數中有可能沒有被使用,函數就拋出異常退出了。就是說要付出額外的構造和析構encrypted的代價。最後的方式就是延後encrypted的定義:code

 1  std::string encryptPassword(const std::string &password)
 2  {
 3     using namespace std;
 4    
 5    if(password.length() < MinimunPasswordLength)
 6     {
 7       throw logic_error("Password is too short!");
 8     } 
 9        string encrypted;
10    ...          //do what you want
11 
12    return encrypted;
13  }    

這樣就能夠了嗎?其實這段代碼也稍有瑕疵,緣由在第九行,encrypted雖然說被定義了,可是卻沒有賦初值,這意味着調用的是自身的默認構造函數。在Effective C++中,建議對對象作的第一次事情就是給他一個初值,一般經過賦值來完成。item4講過經過默認構造函數構造對象而後對其賦值比直接在構造時指定初值效率差。例如以下的代碼:對象

std::string encryptPassword(const std::string &password)
{
    ...
    std::string encrypted;  //default constructor
    encrypted = password; //assignment
    
    encrypt(encrypted);
    return encrypted;
}

更好的作法,是跳過無心義的默認構造函數,經過copy構造函數一次性來完成:blog

std::string encryptPassword(const std::string &password)
{
    ...
    std::string encrypted(password);  //copy constructor
    
    encrypt(encrypted);
    return encrypted;
}
相關文章
相關標籤/搜索