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

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

版权声明:本文为博主原创文章。未经博主同意不得转载。

https://blog.****.net/zhsenl/article/details/37596705

本文为senlie原创。转载请保留此地址:http://blog.****.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构造行为。