尽可能延后的真正意义:你不仅应该延后变量的定义直到非使用不可为止, 甚至应该偿试延迟这份定义直到能给它初始值为止。
//这样不但可以避免不必要的构造和析构,还可以避免无意义的default构造行为
/******************示例
void encrypt(string encrypted);
string encryptPassowrd(const string& password)
{
... //判断长度等
string encrypted(password);
encrypt(encrypted);
return encrypted;
}
***********************/
/****************循环的情况
//A: 一个构造函数 + 一个析构函数 + n个赋值操作
Widget w;
for(int i = 0; i < n; ++i)
{
w = ...;
}
//B: n个构造函数 + n个析构函数
for(int i = 0; i < n; ++i)
{
Widget w(...);
}
//做法A造成w的作用域比作法B更大
//除非(1)你知道赋值成本比“构造+析构”成本低, (2) 你正在处理代码中效率高度敏感的部分, 否则你应该便用B方法
//这样不但可以避免不必要的构造和析构,还可以避免无意义的default构造行为
/******************示例
void encrypt(string encrypted);
string encryptPassowrd(const string& password)
{
... //判断长度等
string encrypted(password);
encrypt(encrypted);
return encrypted;
}
***********************/
/****************循环的情况
//A: 一个构造函数 + 一个析构函数 + n个赋值操作
Widget w;
for(int i = 0; i < n; ++i)
{
w = ...;
}
//B: n个构造函数 + n个析构函数
for(int i = 0; i < n; ++i)
{
Widget w(...);
}
//做法A造成w的作用域比作法B更大
//除非(1)你知道赋值成本比“构造+析构”成本低, (2) 你正在处理代码中效率高度敏感的部分, 否则你应该便用B方法