TITLE: return value optimization and temp lifetimes (Newsgroups: comp.lang.c++.moderated, 7 Mar 97) BERGER: "Micha S. Berger" |> > We all know you can't do |> > int& foo() { |> > int a = 3; |> > return a; |> > } |> > |> > So, on a job interview I was asked about how to return a reference, |> > without invoking new -- since new might lead to a memory link on the |> > part of an unaware user of your class/library. |> > |> > (The case, I forget the details, involved nesting <<, so that you wanted |> > the left side to actually refer to the same object.) |> > |> > Either way, after giving up (mumbling something about g++'s workaround), |> > the interview claims that according to CD2, |> > return Foo(x); |> > will construct a Foo on the CALLER'S stack, not on the current |> > function's. |> > |> > Sounded unlikely to me. Anyone see this written anywhere? BLACK: "Paul Black" |> Section 12.2 of CD2 is probably what you are looking for. Temporaries |> bound to a reference have the same lifetime as the reference. KANZE: James Kanze Not quite. According to 12.2, a temporary bound to a reference persists for the lifetime of the reference *OR* until the end of the scope in which the temporary is created, whichever comes first. In the above case, the scope in which the temporary is created is the function; the temporary must be destructed on leaving the function.