本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:尽可能延后变量定义式的出现。这样做可增加程序的清晰度并改善程序效率。
示例://这个函数过早定义变量“encrypted” std::string encryptPassword(const std::string &password){ using namespace std; string encrypted; if(password.length() < MinimumPasswordLength){ throw logic_error("Password is too short"); } //... return encrypted; }
//这个函数延后"encrypted"的定义,直到真正需要它 std::string encryptPassword(const std::string &password){ using namespace std; if(password.length() < MinimumPasswordLength){ throw logic_error("Password is too short"); } string encrypted; // default-construct encrypted encrypted = password; //赋值给 encrypted encrypt(encrypted); return encrypted; }
//通过copy构造函数定义并初始化 std::string encryptPassword(const std::string &password){ //... std::string encrypted(password); //... }