这个条款在More Effective C++里有进一步的说明,推迟变量的定义被叫做“缓式评估”。

 

产生本条款做法的根本原因是构造和析构函数有开销。

 

文中给出了一个例子,如下:

// 此函数太早定义了变量"encrypted"
string encryptPassword(const string& password)
{
  string encrypted;

  if (password.length() < MINIMUM_PASSWORD_LENGTH) {
     throw logic_error("Password is too short");
  }

  进行必要的操作,将口令的加密版本 
  放进encrypted之中;

  return encrypted;
}

 

 

对象encrypted在函数中并非完全没用,但如果有异常抛出时,就是无用的。但是,即使encryptPassword抛出异常(见条款M15),程序也要承担encrypted构造和析构的开销。所以,最好将encrypted推迟到确实需要它时才定义:

// 这个函数推迟了encrypted的定义,
// 直到真正需要时才定义
string encryptPassword(const string& password)
{
  if (password.length() < MINIMUM_PASSWORD_LENGTH) {
    throw logic_error("Password is too short");
  }

  string encrypted;

  进行必要的操作,将口令的加密版本 
  放进encrypted之中;

  return encrypted;
}

这段代码还不是那么严谨,因为encrypted定义时没有带任何初始化参数。这将导致它的缺省构造函数被调用。

(略)。。。。。。。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2022-12-23
  • 2021-11-26
  • 2021-06-01
  • 2021-10-13
  • 2022-01-12
猜你喜欢
  • 2021-12-02
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2022-02-11
  • 2021-09-08
  • 2021-07-14
相关资源
相似解决方案