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

    版权声明:本文为博主原创文章。未经博主同意不得转载。

    https://blog.csdn.net/zhsenl/article/details/37596705

    本文为senlie原创。转载请保留此地址:http://blog.csdn.net/zhengsenlie


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

    演示样例:
    //这个函数过早定义变量“encrypted”
    std::string encryptPassword(const std::string &password){
    	using namespace std;
    	string encrypted;
    	if(password.length() < MinimumPasswordLength){
    		throw logic_error("Password is too short");
    	}
    	//...
    	return encrypted;
    }

    解析:
    对象 encrypted在此函数中并不是全然未被调用,但假设有个异常被丢出,它就真的没被使用。
    也就是说假设函数 encryptPassword丢出异常,你付出 encrypted的构造成本和析构成本。
    纠正1:
    //这个函数延后"encrypted"的定义。直到真正须要它
    std::string encryptPassword(const std::string &password){
    	using namespace std;
    	if(password.length() < MinimumPasswordLength){
    		throw logic_error("Password is too short");
    	}
    	string encrypted; // default-construct encrypted
    	encrypted = password; //赋值给 encrypted
    	encrypt(encrypted);
    	return encrypted;
    }

    解析:
    encrypted调用的是default构造函数,条款4说了“通过default构造函数构造出一个对象然后对它赋值”比“直接在构造时指定初值”效率差。



    纠正2:

    //通过copy构造函数定义并初始化
    std::string encryptPassword(const std::string &password){
    	//...
    	std::string encrypted(password); 
    	//...
    }

    解析:不仅仅应该延后变量的定义。直到非得使用该变量的前一刻为止,甚至应该尝试延后这份定义直到可以给它初值实參为止。
    这样不仅可以避免构造(析构)非必要对象,还可以避免无意义的default构造行为。



  • 相关阅读:
    对计算机科学与技术专业的认识及未来的规划
    秋季学期学习总结
    自我介绍
    Leetcode每日一题 83. 删除排序链表中的重复元素
    Leetcode每日一题 82. 删除排序链表中的重复元素 II
    Leetcode每日一题 456.132 模式
    Leetcode每日一题 341. 扁平化嵌套列表迭代器
    Leetcode每日一题 191. 位1的个数
    Leetcode每日一题 73. 矩阵置零
    Leetcode每日一题 150. 逆波兰表达式求值
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10818221.html
Copyright © 2011-2022 走看看