Effective C++ Item 26 尽可能延后变量定义式的出现时间

来源:互联网 发布:ssm框架oa系统源码 编辑:程序博客网 时间:2024/05/21 18:37

本文为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在此函数中并非完全未被调用,但如果有个异常被丢出,它就真的没被使用。
也就是说如果函数 encryptPassword丢出异常,你付出 encrypted的构造成本和析构成本。
纠正1:
//这个函数延后"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 encryptedencrypted = password; //赋值给 encryptedencrypt(encrypted);return encrypted;}

解析:
encrypted调用的是default构造函数,条款4说了“通过default构造函数构造出一个对象然后对它赋值”比“直接在构造时指定初值”效率差。

纠正2:
//通过copy构造函数定义并初始化std::string encryptPassword(const std::string &password){//...std::string encrypted(password); //...}

解析:不只应该延后变量的定义,直到非得使用该变量的前一刻为止,甚至应该尝试延后这份定义直到能够给它初值实参为止。
这样不仅能够避免构造(析构)非必要对象,还可以避免无意义的default构造行为。



0 0
原创粉丝点击