author:
- luixiao1223
title: 尽量延迟变量定义的出现时间
Why
- 过早的构造成本
- 有可能根本就不会用到
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;
}
这两段代码各有利弊,但是如何使用他们?除非你知道赋值陈本比构造+析构成本低,你正在处理的代码中效率高度敏感。否则你应该使用第二种方式。
加粗样式