如果定义了一个带有构造函数和析构函数的变量,那么程序就要承受构造和析构的成本----你必须考虑这件事情
考虑以下函数:
std::string encryptPassword(const std::string& password) { using namespace std; string encrypted; if(password.length() < MiniLength) { throw logic_error("Password is too short"); } 。。。 return encrypted; } 上述函数先定义了变量encrypted,但是抛出异常时该变量并没有使用。因此我们应该在抛出异常之后再定义它。 std::string encryptPassword(const std::string& password) { using namespace std; if(password.length() < MiniLength) { throw logic_error("Password is too short"); } <pre name="code" class="cpp"> string encrypted;//晚一点定义encrypted encrypted = password 。。。 return encrypted;} 上述函数还存在一个问题你可能已经发现了,encrypted变量先调用自己的默认构造函数,再去进行一次拷贝狗造显然效率会低呀!所以这样可能更合适一点:
std::string encryptPassword(const std::string& password) { using namespace std; if(password.length() < MiniLength) { throw logic_error("Password is too short"); } <pre name="code" class="cpp"> string encrypted(password);//晚一点定义encrypted 。。。 return encrypted; } 对于循环来说,应该如何处理呢?考虑以下代码 //方法A Widget w; for(int i = 0;i<n;++i) { w = ... } //方法B for(int i=0;i<n;i++) { Widget w(...); } <pre name="code" class="cpp">//在A中: 1个构造函数+1个析构函数+n个赋值操作 //在B中: n个构造函数+n个析构函数 我们该如何选择:如果一个类的赋值成本低于一组构造+析构成本,A方法整体而言比较搞笑,随着N增大更加明显。
否则应该采用B方法。并且B的作用域限定于循环内部,更易于理解和规范。所以如果你坚持采用A方法的前提是:
1.你知道赋值成本比 构造+析构 成本低
2.你正在处理代码中效率高度敏感的部分