条款 26 :尽可能延后变量定义式的出现时间

条款 26 :尽可能延后变量定义式的出现时间

** Postpone variable definitions as long as possible**

  1. 只要你定义了一个变量而且其类型带有构造和析构函数,那么程序的控制流到达这个定义式的时候你就要承受构造成本。

你会说你不能定义一个不用的变量,话不说这么早,我们来看下列代码:

//这个函数过早定义变量encrypted
std::string encryptPassword(const std::string& password){
	using namespace std;
	string encrypted;
	if(password.length()<MininumPasswordLength){
		throw logic_error("Password is too short");
	}
	...//必要动作,能将一个加密后的密码置入变量encrypted内
	return encrypted;
}

上面这个代码,变量encrypted并非完全被使用,如果抛出异常的话,那么这个变量就没派上用场但是你却付出的构造和析构的时间。

//这个函数延后定义变量encrypted,直到真正需要他
std::string encryptPassword(const std::string& password){
	using namespace std;
	if(password.length()<MininumPasswordLength){
		throw logic_error("Password is too short");
	}
	string encrypted;
	...//必要动作,能将一个加密后的密码置入变量encrypted内
	return encrypted;
}

回顾条款四,通过构造函数再赋值比直接在构造时给初值慢,我们看下面两个函数方式

void encrypt(std::string& s);//在合适的地点对s加密
std::string encryptPassword(const std::string& password){
	using namespace std;
	if(password.length()<MininumPasswordLength){
		throw logic_error("Password is too short");
	}
	string encrypted;
	encrypted=password;//defaul构造
	encrypt(encrypted);
	...//必要动作,能将一个加密后的密码置入变量encrypted内
	return encrypted;
}

std::string encryptPassword(const std::string& password){
	using namespace std;
	if(password.length()<MininumPasswordLength){
		throw logic_error("Password is too short");
	}
	string encrypted(password);//copy构造函数
	encrypt(encrypted);
	...//必要动作,能将一个加密后的密码置入变量encrypted内
	return encrypted;
}

遇上循环怎么办呢?

//方法A:定义于循环外
Widget w;
for(int i=0;i<n;++i){
	w=xxx;
	...
}
//方法B:定义于循环内
for(int i=0;i<n;++i){
	Widget w;
	w=xxx;
	...
}

我们来看看方法A,B的时间开销对比:
方法A:1个构造函数+一个析构函数+n个赋值操作
方法B:n个构造函数+n个析构函数
所以至于内外我们就要看具体类的构造析构和赋值的时间成本了。

请记住

尽可能延后变量定义式的出现。这样做可增加程序的清晰度并改善程序效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值