zoukankan      html  css  js  c++  java
  • [Effective C++ --026]尽可能延后变量定义式的出现时间

    引言

    每一次构造和析构都需要成本,因此我们在设计代码的时候,应该尽可能考虑到构造和析构的成本。

    第一节 延后实现

    考虑有以下的代码:

     1 void encrypt(string& s);
     2 string encryptPassword(const sting& password) {
     3     string encrypted;
     4     if (xxxxx) {
     5          throw logic_error("xxxxxx");
     6     }  
     7     encrypted = password;
     8     encrypt(encrypted);
     9 
    10     return encrypted;
    11 }

    在上述代码中,encrypted在被创建过后,如果抛出异常,那么就不会再使用。但是我们还得负担他的构造和析构成本。

    我们可以考虑改成这样:

     1 void encrypt(string& s);
     2 string encryptPassword(const sting& password) {
     3     if (xxxxx) {
     4          throw logic_error("xxxxxx");
     5     }  
     6     string encrypted;
     7     encrypted = password;
     8     encrypt(encrypted);
     9 
    10     return encrypted;
    11 }

    这样虽然很好的避免了上面的析构和构造问题,但是在第6行还是会调用string的默认的构造函数。

    因此我们可以考虑再这样修改:

     1 void encrypt(string& s);
     2 string encryptPassword(const sting& password) {
     3     if (xxxxx) {
     4          throw logic_error("xxxxxx");
     5     }  
     6     string encrypted(password);  // 使用拷贝构造函数定义并初始化
     7     encrypt(encrypted);
     8 
     9     return encrypted;
    10 }

    可以避免无谓的默认构造行为。

    第二节 循环

    代码写的多了,都会出现下面这两种情况:

    1.

    1 Widget W;
    2 for (int i = 0; i < n; i++) {
    3     w = .....
    4     .......
    5 }

    2.

    1 for (int i = 0; i < n; i++) {
    2     Widget w( .....);
    3     .......
    4 }

    方法1:1个构造函数+1个析构函数+n个赋值操作

    方法2:n个构造函数+n个析构函数

    如果class的一个赋值成本低于一组构造+析构成本,那么做法A比较高效。否则B或许好些。

    ◆总结

    1.尽可能延后变量定义式的出现。这样做可增加程序的清晰度并改善程序效率。

  • 相关阅读:
    二逼青年暑假深圳面试记
    poj2032Square Carpets(IDA* + dancing links)
    JBoss 系列七十:一个简单的 CDI Web 应用
    cocos2d-x 截取屏幕可见区域
    HDU3863:No Gambling
    SQL Server配置管理WMI问题
    Inno_setup制作升级包必须面临的几个问题
    Log4j发送邮件
    为github帐号添加SSH keys(Linux和Windows)
    Ubuntu常用命令
  • 原文地址:https://www.cnblogs.com/hustcser/p/4206253.html
Copyright © 2011-2022 走看看