首页 > 其他分享 >Item26:尽可能延后变量定义式的出现时间

Item26:尽可能延后变量定义式的出现时间

时间:2024-04-08 14:56:39浏览次数:22  
标签:std string encrypted 定义 延后 尽可能 Item26 password 变量

芝士wa
2024.4.8


“只要你定义了一个变量而其类型带有一个构造函数或析构函数,那么当程序的控制流到达这个变量定义式时,你便得承担构造成本;当这个变量离开其作用域时,你便得承受析构成本,即使这个变量最终未被使用,仍需耗费这些成本,所以你应该尽可能避免这些情形”

坏的例子,过早的定义变量encrypted:

std::string encryptPassword(const std::string& password){
using namespace std;
string encrypted;
if(password.length()<MinimumPasswordLength){
  throw logic_error("Password is too short");
}
...
return encrypted;
}

如果有异常被丢出,那么encrypted未被使用,构造和析构都是浪费。因此,应该将string encrypted移到判断语句之后:

std::string encryptPassword(const std::string& password){
using namespace std;
if(password.length()<MinimumPasswordLength){
  throw logic_error("Password is too short");
}
string encrypted;
...
return encrypted;
}

但是这段代码仍有问题,参考Item4,在定义变量的时候应该为其赋初值,并且应当通过拷贝构造的方式,正确的例子如下:

std::string encryptPassword(const std::string& password){
using namespace std;
if{...}
string encrypted(password);
...
return encrypted;
}

如果变量只在循环内使用,那么把它定义到循环还是定义在循环内?

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

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

第一种写法的成本为:1个构造函数+1个析构函数+n个赋值操作
第二个写法的成本为:n个构造函数+n个析构函数

如果classes的一个赋值成本低于一组构造+析构成本,第一种做法更高效,但是会造成w的作用域更大,因此如果对于代码中高敏感的部分,应该采用做法二。

标签:std,string,encrypted,定义,延后,尽可能,Item26,password,变量
From: https://www.cnblogs.com/cheese-wa/p/18121146

相关文章