Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!lll-winken!ames!bionet!agate!darkstar!terra!daniel From: daniel@terra.ucsc.edu (Daniel Edelson) Newsgroups: comp.std.c++ Subject: Re: Order of destructor calls for auto objects Keywords: temporaries Message-ID: <10589@darkstar.ucsc.edu> Date: 3 Jan 91 22:33:44 GMT References: lots... Sender: usenet@darkstar.ucsc.edu Reply-To: daniel@terra.ucsc.edu (Daniel Edelson) Organization: University of California, Santa Cruz Lines: 47 In article <1991Jan1.015110.329@lia> jgro@lia.com (Jeremy Grodberg) writes: > >E&S 12.2 requires temporaries to be destroyed before the "exit from >the scope in which the temporary is created." .... >-- >Jeremy Grodberg >jgro@lia.com Unless, of course, a reference is bound to the temporary, in which case the temporary must not be destroyed until the reference is. This may require a temporary to exist beyond the scope in which it is constructed. For example: struct T { }; struct U { T & tr; U(T & r) : tr(r) { } }; T maketemp() { T t; return t; } void foo() { U * p = new U(maketemp()); return p; } main() { U * p = foo(); } In this example an object of type U gets created containing a reference to a temporary T. How is the compiler to know when it can destroy the temporary? This looks like a rather ugly problem. Cfront seems to copy the temporary to the outer scope. So in fact, the temporary gets destroyed more than once. This example is not an error because it is also constructed more than once, once with the normal constructor and once with the copy constructor. But woe to the programmer who neglects to build reference counts into his/her locks! I'm sure than when aliases (pointers) are introduced a large number of cfront (and other) compiler bugs are revealed based on lifetime of temporaries. --- Daniel Edelson | C++ virtual garbage recycler: daniel@cis.ucsc.edu, or | ``Recycle your garbage. Please don't ...!sun!practic!peren!daniel | make me come and copy after you.''