I am trying to understand what does the C++ standard say about how/when the destructor should be called when an object is returned from the function - Consider this simple struct and two functions -
#include <iostream>
int g = 0;
struct foo {
int myid;
foo() {
myid = g;
g++;
std::cout << "Created " << myid << std::endl;
}
~foo() {
std::cout << "Destroyed " << myid << std::endl;
}
};
foo bar(void) {
int i = 0;
for (foo s; i < 10; i++) {
if (i == 5)
return s;
}
}
foo bar2(void) {
int i = 0;
foo s;
for (; i < 10; i++) {
if (i == 5)
return s;
}
}
int main() {
bar();
bar2();
return 0;
}
I am trying to track how many times the destructor is called. The output from the above program is -
Created 0
Destroyed 0
Destroyed 0
Created 1
Destroyed 1
I can understand the behavior of bar2
. An object is created once and destroyed (I believe the destructor is called from main). But in bar
when the object is declared inside the loop. It cases the destructor to be called twice. What is the reason for this discrepancy?
Is it the case that the standard leaves this behavior to the implementation (because of copy elision?) and g++ just choses this behavior for the two cases? If so how can I write this function so that I get predictable behavior. I need the destructor to be called the exact same number of times as the constructor (and preferably in the reverse order). I am okay with the destructor being called twice as long as the constructor is being called twice too. The reason is because I am allocating some data inside the constructor and freeing it inside the destructor.