From Effective C++ Item26
给定如下的程序:
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的定义:
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构造函数一次性来完成:
std::string encryptPassword(const std::string &password) { ... std::string encrypted(password); //copy constructor encrypt(encrypted); return encrypted; }