Effective C++(尽量压后变量的定义)


author:

  • luixiao1223
    title: 尽量延迟变量定义的出现时间

Why

  1. 过早的构造成本
  2. 有可能根本就不会用到
std::string encryptPassword(const std::string& password)
{
    using namespace std;
    string encrypted;

    if (password.length() < MininumPasswordLength) {
        throw logic_error("Password is too short"); // 这里返回的时候,支付了string的构造成本。但是毫无用处。
    }
    return encrypted;
}

最好在构造的时候赋值

好处:可以避免多余的赋值操作

std::string encryptPassword(const std::string& password)
{
    std::string encrypted;
    encrypted = password;
    encrypt(encrypted);
    return encrypted;
}

// vs 下面的代码


std::string encryptPassword(const std::string& password)
{
    std::string encrypted(password); // 少一次赋值
    encrypt(encrypted); 
    return encrypted
}

循环怎么办?

问题

// Plan A
Widget w;

for (int i = 0; i < n; ++i)
{
    w = ...
}

// VS next code snippet

// Plan B
for (int i = 0; i < n; ++i)
{
    Widget w;
}

这两段代码各有利弊,但是如何使用他们?除非你知道赋值陈本比构造+析构成本低,你正在处理的代码中效率高度敏感。否则你应该使用第二种方式。
加粗样式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值