Alex Alex - 2 months ago 17
C++ Question

Constructor and destructor order on static allocation

I wrote this simple code, I expected a different result.

struct Test {
int value_;
Test(): value_(0) {
std::cout << "Constructor: "<< value_ << "\n";
}

Test(int value): value_(value) {
std::cout << "Constructor: "<< value_ << "\n";
}

~Test() {
std::cout << "Destructor: "<< value_ << "\n";
}
};

int main(int argc, char **argv) {
Test t;
t = Test(10);
t = Test(15);
t = Test(20);
t = Test(25);
}


And the result:

Constructor: 0
Constructor: 10
Destructor: 10
Constructor: 15
Destructor: 15
Constructor: 20
Destructor: 20
Constructor: 25
Destructor: 25
Destructor: 25


I was surprised because it did not expect the last line would be repeated. Why
Destructor: 0
was not called?

Answer

The first "Destructor: 25" is from the destruction of the temporary object created by Test(25); the second is from the destruction of t into which that has been copied.

Other than that last "Destructor:" line and the first "Constructor:", all the output is from the creation and destruction of those temporary objects. There is no "Destructor: 0" because you never make a temporary object with value 0, and by the time t is destroyed its value is no longer 0.

Comments