直到不得不使用该变量为止

如果变量没有被使用,那么就白白进行了构造函数和析构函数

  1. string funcA(const string& password) {
  2. string pass;
  3. if(password.size() < minSize) {
  4. throw "Password is too short";
  5. }
  6. return pass;
  7. }

不如改为

  1. string funcA(const string& password) {
  2. if(password.size() < minSize) {
  3. throw "Password is too short";
  4. }
  5. string pass;
  6. return pass;
  7. }

能够给变量初值为止

调用变量的缺省构造函数再将其赋值,和直接在构造变量时赋初值,后者效率更高。

  1. string funcA(const string& password) {
  2. string pass;
  3. pass = password;
  4. return pass;
  5. }

不如改为

  1. string funcA(const string& password) {
  2. string pass(password);
  3. return pass;
  4. }

不仅能避免没有必要的构造和析构,还可以避免没有必要的default构造函数

循环

  1. Widget w;
  2. for(int i = 0;i < n;i++) {
  3. w = xxx;
  4. }
  1. for(int i = 0;i < n;i++) {
  2. Widget w(xx);
  3. }

第一个版本:1次构造函数,1次析构函数,n次赋值操作
第二个版本:n次构造函数,n次析构函数
当赋值成本 远小于 构造析构时,选择第一个版本;代码对于效率极其敏感时,选择第一个版本。除此之外,选择第二个版本。