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

本文为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 encrypted
	encrypted = password; //赋值给 encrypted
	encrypt(encrypted);
	return encrypted;
}

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

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

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



Effective C++ Item 26 尽可能延后变量定义式的出现时间,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。