Order of Object destruction

Neophytos Michael nmichael@cs.princeton.edu
Fri May 23 10:48:00 GMT 2003


Consider the following small program that attempts to discover the
order in which temp objects are being destroyed:

----------------------------------------------------------------------
#include <iostream>
using namespace std;

int k = 0;

class A {
public:
   int y;

   A() : y(k++) {
     cout << "Constructor called: Object #: " << y << endl;
   }
   A(const A& a) {
     y = k++;
     cout << "Copy constructor called:\n   Old Object #: "
          << a.y << "  New Object #: " << y << endl;
   }
   ~A() {
     cout << "Destructor called: Object #: " << y << endl;
   }
};

A foo(A z) {
   cout << "In foo Object #: " << z.y << endl;
   return z;
}

int main() {
   A a;

   cout << foo(a).y << endl;
   return 0;
}
----------------------------------------------------------------------

The output of the program is given below:
----------------------------------------------------------------------
$ ./a.exe
Constructor called: Object #: 0
Copy constructor called:
    Old Object #: 0  New Object #: 1
In foo Object #: 1
Copy constructor called:
    Old Object #: 1  New Object #: 2
2
Destructor called: Object #: 2
Destructor called: Object #: 1
Destructor called: Object #: 0
-----------------------------------------------------------------------

As expected the copy constructor is called twice.  Once to create the
argument to function foo (this is object #1), and another to create
the temp object that presumably lives in the frame of main (object
#2).

What I find peculiar is that object #1 is not destroyed immediately
after we return from function foo.  That is where its scope ends so I 
would expect it's destrucion to take place then.  In fact the printing 
of number 2 takes place, then object #2 (the temp object) is destroyed 
and finally object #1.  I would expect object #1 to be destroyed before #2.

Does the standard specify the exact order of destruction in this case? 
I am using g++ 3.2 on cygwin.  I posted this to the c++ newsgroups and 
someone mentioned that visual c++ destroys object #1 first and then #2. 
  Is this a bug in gcc/visual-c++ or does the standard not specify the 
order of object destruction in this case?

Neophytos



More information about the Gcc-help mailing list