Home > Software design >  C destructor called timing for returned value
C destructor called timing for returned value

Time:03-07

Consider C code as below:

struct V {
  int s;
  V(int s): s(s) {}
  ~V() { cout << "Destructor\n"; }
};

V f() {
  V x(2);
  return x;
}

int main(){
  V a = f();
  cout << "Function End\n";
  return 0;
}

The execution result shows that the destructor is called only once.

Function End
Destructor

However, if I add a meaningless if statement as below, the destructor is called twice.

V f() {
  if(false) return V(3);
  V x(2);
  return x;
}
Destructor
Function End
Destructor

Why can this happen? Is there some points to avoid calling destructor twice?

CodePudding user response:

In the first example, NRVO (Named Return Value Optimization) may kick in and elide the copy in return x;.

When you have two exit paths, not returning the same variable, NRVO is less likely to kick in and you'll actually get a copy, even though if(false) is never going to be true.

The below would most likely also elide the copy because x is returned in all paths that leads to return.

V f() {
    V x(2);
    if (false) x = V(3);
    return x;
}
  • Related