TITLE: object lifetimes and optimization (Newsgroups: comp.std.c++, 7 Nov 96) [ Scott is the author of "Effective C++" and "More Effective C++" -adc ] MEYERS: smeyers@teleport.com (Scott Meyers) At some point in the "what is a reference?" wars, somebody wrote: | : Correct. You're interpretation corresponds to mine, however... The | : lifetime of an object depends on whether it has a non-trivial | : constructor or not. Do references have a non-trivial constructor? The lifetime of an object now depends on more than whether it has a non-trivial constructor. It also depends on whether the object in question is involved in one or more applications of what was originally the return value optimizaion (ARM 12.1.1c). From section 12.8 of the September 1996 DWP: 15Whenever a class object is copied and the original object and the copy have the same type, if the implementation can prove that either the original object or the copy will never again be used except as the result of an implicit destructor call (_class.dtor_), an implementa- tion is permitted to treat the original and the copy as two different ways of referring to the same object and not perform a copy at all. In that case, the object is destroyed at the later of times when the original and the copy would have been destroyed without the optimization.7) [Example: class Thing { public: Thing(); ~Thing(); Thing(const Thing&); Thing operator=(const Thing&); void fun(); }; void f(Thing t) { } void g(Thing t) { t.fun(); } int main() { Thing t1, t2, t3; f(t1); g(t2); g(t3); t3.fun(); } Here t1 does not need to be copied when calling f because f does not use its formal parameter again after copying it. Although g uses its parameter, the call to g(t2) does not need to copy t2 because t2 is not used again after it is passed to g. On the other hand, t3 is used after passing it to g so calling g(t3) is required to copy t3. ] _________________________ 7) Because only one object is destroyed instead of two, and one copy constructor is not executed, there is still one object destroyed for each one constructed.