• 仅当需要时再给变量定义


    From Effective C++ Item26

    给定如下的程序:

     std::string encryptPassword(const std::string &password)
     {
        using namespace std;
       string encrypted;
       if(password.length() < MinimunPasswordLength)
        {
          throw logic_error("Password is too short!");
        } 
       ...          //do what you want
    
       return encrypted;
     }

    对象encrypted在此函数中有可能没有被使用,函数就抛出异常退出了。就是说要付出额外的构造和析构encrypted的代价。最后的方式就是延后encrypted的定义:

     1  std::string encryptPassword(const std::string &password)
     2  {
     3     using namespace std;
     4    
     5    if(password.length() < MinimunPasswordLength)
     6     {
     7       throw logic_error("Password is too short!");
     8     } 
     9        string encrypted;
    10    ...          //do what you want
    11 
    12    return encrypted;
    13  }    

    这样就可以了吗?其实这段代码也稍有瑕疵,原因在第九行,encrypted虽说被定义了,但是却没有赋初值,这意味着调用的是自身的默认构造函数。在Effective C++中,建议对对象做的第一次事情就是给他一个初值,通常通过赋值来完成。item4讲过通过默认构造函数构造对象然后对其赋值比直接在构造时指定初值效率差。例如如下的代码:

    std::string encryptPassword(const std::string &password)
    {
        ...
        std::string encrypted;  //default constructor
        encrypted = password; //assignment
        
        encrypt(encrypted);
        return encrypted;
    }

    更好的做法,是跳过无意义的默认构造函数,通过copy构造函数一次性来完成:

    std::string encryptPassword(const std::string &password)
    {
        ...
        std::string encrypted(password);  //copy constructor
        
        encrypt(encrypted);
        return encrypted;
    }
  • 相关阅读:
    VDOM configuration
    Fortinet Security Fabric
    Gartner 2018 年WAF魔力象限报告:云WAF持续增长,Bot管理与API安全拥有未来
    installns
    vyos 基础配置
    vyatta的fork开源版本vyos
    vyos User Guide
    图论----同构图(详解)
    Educational Codeforces Round 21(A.暴力,B.前缀和,C.贪心)
    2017年中国大学生程序设计竞赛-中南地区赛暨第八届湘潭市大学生计算机程序设计大赛游记心得
  • 原文地址:https://www.cnblogs.com/edmundli/p/4368100.html
Copyright © 2020-2023  润新知