|
Order of Object destruction: msg#00205gcc.help
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 |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Dear Gcc-help - Great Books on Best Practices in Business and Management: 00205, jasmine |
|---|---|
| Next by Date: | Re: Order of Object destruction: 00205, Eljay Love-Jensen |
| Previous by Thread: | Dear Gcc-help - Great Books on Best Practices in Business and Managementi: 00205, jasmine |
| Next by Thread: | Re: Order of Object destruction: 00205, Eljay Love-Jensen |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |