标签:
最近在看Scott Meyers的《Effective
C++》改善程序与设计的55个具体做法(第三版),水平有限,有些东西没能完全理解,捡一些自己能理解的并很容易记住的点来分享下!有的是原文的内容的直接摘抄,敬请谅解!
这条建议是:尽可能地延后定义式的出现时间。这么做的意义在于:可增加程序的清晰度并改善程序的效率。这对小程序来说可能体会的不深或者说影响不大,但是我们依然要保持良好的代码习惯和提高代码段的质量,不是吗?
作者给的解释是:只要你定义了一个变量而其类型带有一个构造函数或者析构函数,那么当函数的控制流到达这个变量定义式时,我们要承受构造成本,当离开作用域时,需要承受析构成本。即使这个变量最终你没有去使用它,这么成本仍然需要消耗,所以这种情况最好不要发生!
例如文中给的例子:
std::string encryptPasswoed(const std::string& password)
{
using namespace std;
string encrypted;
if (password.length()<MinimumPasswordLength)
{
throw...//抛出异常
}
....
return encrypted;
}
std::string encryptPasswoed(const std::string& password)
{
using namespace std;
if (password.length()<MinimumPasswordLength)
{
throw...//抛出异常
}
string encrypted;
....
return encrypted;
}
std::string encryptPasswoed(const std::string& password)
{
using namespace std;
if (password.length()<MinimumPasswordLength)
{
throw...//抛出异常
}
string encrypted(password);//通过copy构造函数定义并初始化
encrypt(encrypted);
....
return encrypted;
}
//方法A:定义于循环外
Widget w;
for(int i = 0; i < n ; i++)
{
w = 跟i有关的某个值;
}
//方法B:定义于循环内
for(int i = 0; i < n ; i++)
{
Widget w;//跟i有关的某个值;
}
标签:
原文地址:http://blog.csdn.net/u013782830/article/details/51337321