您的位置:首页 > 其它

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

2010-03-05 17:49 267 查看
原代码:

std::string encryptPassword(const std::string& password)
{
  using namespace std;
string encrypted;//声明过早,如果下面抛出异常,此声明增加负担

if (password.length() < MinimumPasswordLength)
{
   throw logic_error("Password is too short");
}
  ... // do whatever is necessary to place an encrypted version of password in encrypted
return encrypted;
}


 

修改后:避免构造和析构无用对象,而且还可以避免不必要的缺省构造。

std::string encryptPassword(const std::string& password)
{
  ... // check length
std::string encrypted(password); // define and initialize via copy constructor
encrypt(encrypted);
return encrypted;
}


 

下面这两个大致的结构中哪个更好一些?

// Approach A: define outside loop
Widget w;
for (int i = 0; i < n; ++i)
{
w = some value dependent on i;
}
// Approach B: define inside loop
for (int i = 0; i < n; ++i)
{
Widget w(some value dependent on i);
... ...
}


 

对于 Widget 的操作而言,两个方法的成本:

方法 A:1 个构造函数 + 1 个析构函数 + n 个赋值。

方法 B:n 个构造函数 + n 个析构函数。

对于那些赋值的成本低于一个构造函数+析构函数对的成本的类,方法 A 通常更高效。特别是在 n 变得很大的情况下。否则,方法 B 可能更好一些。因此,除非你确信以下两点:(1)赋值比构造函数 /析构函数对成本更低,而且(2)你正在涉及你的代码中的性能敏感的部分,否则,你应该默认使用方法 B。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string constructor