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; }