/*条款26: 尽可能延后变量定义的出现时间*/
#include<iostream>
#include<string>
#define MinimumPasswordLength 32
using namespace std;
void encrypt(const string &s){
}
string encryptPassword(const string &password){
// using namespace std;
//string encrypted;//如果在这个位置定义 函数执行无论是否有异常抛出总是会有encryted的构造与析构的开销
if (password.length() < MinimumPasswordLength){
throw logic_error("Password is too short");
}
//...
/* string encrypted; 一次构造
encrypted = password; 一次拷贝赋值
encrypt(encrypted);*/
string encrypted(password);//一次构造并初始化
encrypt(encrypted);
return encrypted;
}
class A{
public:
A(int i){
}
};
const int N = 10;
int main(){
A a(1);// 一次构造 一次析构
for (int i = 0; i < N; ++i){
a = i;//某个值 n个赋值
//....
}
for (int i = 0; i < N; ++i){
A b = i;//某个值 n个构造 n个析构
}
//考虑 赋值成本低于一组构造与析构 第一个循环较优,否则第二个循环较优
system("pause");
return 0;
}
条款26: 尽可能延后变量定义的出现时间
最新推荐文章于 2015-09-28 17:57:19 发布