您的位置:首页 > 其它

条款26: 尽可能延后变量定义的出现时间

2015-09-06 15:19 218 查看
/*条款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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: