尽可能延后变量定义式的出现时间(Effective_C++(26))

本文探讨了在编程中定义和使用对象时如何避免不必要的构造和析构开销,通过将对象定义与使用合并,并在定义时提供初值来提高效率。同时,针对循环操作进行了效率对比分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、定义一个对象,往往意味着必须承担构造成本,离开作用域,必须承担析构成本。即使这个对象没有使用过。


二、你可能会认为,不会定义一个不使用的对象。考虑下面的情况下,定义一个对象,执行其他操作,然后使用对象,假如在执行其他操作的时候,出现异常,就导致构造和析构了一个没有使用的对象

   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;
    }

解决办法是:一个对象的定义和使用,放在一起,中间尽量不要插入其他操作。也就是说,等到真正使用的时候,才去定义:

    std::string encryptPassword(const std::string& password){
        using namespace std;    
        if(password.length() < MinimumPasswordLength){
            throw logic_error("Password is too short");
        }
        string encrypted;
        ...         //开始加密
        return encrypted;
    }

另外,就是在定义时最好给与一个初值(参见条款四),复制构造比先构造,再赋值效率更高


    std::string encryptPassword(const std::string& password){
        using namespace std;    
        if(password.length() < MinimumPasswordLength){
            throw logic_error("Password is too short");
        }
        string encrypted;
        **encrypted=password;**
        ...         //开始加密
        return encrypted;
    }

再考虑下面代码:


    std::string encryptPassword(const std::string& password){
        using namespace std;    
        if(password.length() < MinimumPasswordLength){
            throw logic_error("Password is too short");
        }
        string encrypted(password);
        ...         //开始加密
        return encrypted;
    }

明显下面的效率更高


三、考虑有循环的情况

//A :变量定义于循环外
    Widget w;
    for(int i = 0; i < n; i++){
        w = 某个操作;
        ...
    }


    //B:变量定义于循环内
    for(int i = 0; i < n; i++){
        Widget w(某个操作);
      ...
    }

A: 1个构造函数 + 1个析构函数 + n个赋值函数
B: n个构造函数 + n个析构函数
我们开始比较:如果Widget的构造析构成本比赋值成本要高的话,无疑A的做法总体效率要高;反之则B的做法效率高。另外,需要考虑,放在循环外,放大了对象的作用域


参考:Effective C++(侯捷译)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值