Effective C++条款32: 尽可能地推迟变量的定义

这个条款在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定义时没有带任何初始化参数。这将导致它的缺省构造函数被调用。

(略)。。。。。。。
原文地址:https://www.cnblogs.com/helloweworld/p/3116004.html