Alex
Alex

Reputation: 3381

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?

Upvotes: 3

Views: 167

Answers (2)

R Sahu
R Sahu

Reputation: 206577

The first of those lines corresponds to the destruction of the temporary object.

The second of those lines corresponds to the destruction of t.

When t is destructed, its value_ is 25 since you used

t = Test(25);

as the last line in main.

Upvotes: 1

Gareth McCaughan
Gareth McCaughan

Reputation: 19971

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.

Upvotes: 5

Related Questions