一、定义一个对象,往往意味着必须承担构造成本,离开作用域,必须承担析构成本。即使这个对象没有使用过。
二、你可能会认为,不会定义一个不使用的对象。考虑下面的情况下,定义一个对象,执行其他操作,然后使用对象,假如在执行其他操作的时候,出现异常,就导致构造和析构了一个没有使用的对象:
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;
}
解决办法是:一个对象的定义和使用,放在一起,中间尽量不要插入其他操作。也就是说,等到真正使用的时候,才去定义:
std::string encryptPassword(const std::string& password){
using namespace std;
if(password.length() < MinimumPasswordLength){
throw logic_error("Password is too short");
}
string encrypted;
... //开始加密
return encrypted;
}
另外,就是在定义时最好给与一个初值(参见条款四),复制构造比先构造,再赋值效率更高:
std::string encryptPassword(const std::string& password){
using namespace std;
if(password.length() < MinimumPasswordLength){
throw logic_error("Password is too short");
}
string encrypted;
**encrypted=password;**
... //开始加密
return encrypted;
}
再考虑下面代码:
std::string encryptPassword(const std::string& password){
using namespace std;
if(password.length() < MinimumPasswordLength){
throw logic_error("Password is too short");
}
string encrypted(password);
... //开始加密
return encrypted;
}
明显下面的效率更高
三、考虑有循环的情况
//A :变量定义于循环外
Widget w;
for(int i = 0; i < n; i++){
w = 某个操作;
...
}
//B:变量定义于循环内
for(int i = 0; i < n; i++){
Widget w(某个操作);
...
}
A: 1个构造函数 + 1个析构函数 + n个赋值函数
B: n个构造函数 + n个析构函数
我们开始比较:如果Widget的构造析构成本比赋值成本要高的话,无疑A的做法总体效率要高;反之则B的做法效率高。另外,需要考虑,放在循环外,放大了对象的作用域
参考:Effective C++(侯捷译)