条款 26 :尽可能延后变量定义式的出现时间
** Postpone variable definitions as long as possible**
- 只要你定义了一个变量而且其类型带有构造和析构函数,那么程序的控制流到达这个定义式的时候你就要承受构造成本。
你会说你不能定义一个不用的变量,话不说这么早,我们来看下列代码:
//这个函数过早定义变量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个析构函数
所以至于内外我们就要看具体类的构造析构和赋值的时间成本了。
请记住
尽可能延后变量定义式的出现。这样做可增加程序的清晰度并改善程序效率。