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?