This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Order of Object destruction


Eljay Love-Jensen wrote:
Hi Neophytos,

Yes, the order of destruction is specified, due in no small part to the lifespan of a temporary being well-defined.

Effectively, the temporary object lives until the end-of-statement semicolon.

As I understand it (I've never needed to tried this), if there were an alias to it, it would live until the end of the extant of alias. For example:
A a;
A& b = foo(a);
// a and b are live.
cout << a.y << endl;
cout << b.y << endl; // Okay.


Before the standard's committee nailed the issue, compiler vendors were inconsistent when the temporary object was destructed. Which lead to all sorts of non-portable code and frustrated programmers.

--Eljay

The example that you show I understand and it's fine. But the two objects I was refering two was not "a" and "b" as you have above, but "b" and the temprary object created by the copy constructor once function foo is entered.


Look at the code again:
A foo(A z) {
  cout << "In foo Object #: " << z.y << endl;
  return z;
}

int main() {
  A a;

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

When the call foo(a) is made the copy constructor is called and makes a new object "z". This object "z" is supposed to be desposed off when it goes out of scope.

When the return happens in foo, the copy constructor is called again and given "z" as an argument (a reference to "z") it creates a new object (let's call it "b" as you did above). When "b" gets created there is no reference to "z" anymore (and that's why I don't understand your example above).

I was asking which was supposed to be desposed of first "z" or "b"? Visual C++ disposes "z" first and then "b". g++ does the opposite. Does the standard say which has to go first? If it does then one of the two compilers is in error.

Thanks,
Neophytos


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]