My first example is not correct --- according to the standard, the lifetime of the temporary should be extended. The second example is an user error.
C++ standard says this in 12.2.5: " The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except: — A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. — A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call. — The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement. — A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer. [Example: struct S { int mi; const std::pair<int,int>& mp; }; S a { 1, {2,3} }; S* p = new S{ 1, {2,3} }; // Creates dangling reference — end example ] [ Note: This may introduce a dangling reference, and implementations are encouraged to issue a warning in such a case. — end note ] " David On Sun, Dec 2, 2012 at 4:31 AM, Olivier Ballereau <olivier.baller...@gmx.net> wrote: > Hello David, > > Sorry to come so late into the discussion, but... > > On 21/06/12 00:50, Xinliang David Li wrote: >> One of the most common runtime errors we have seen in gcc-4_7 is >> caused by dangling references to temporaries whole life time have >> ended >> >> e.g, >> >> const A& a = foo(); >> >> or >> foo (A());// where temp's address is saved and used after foo. >> >> Of course this is user error according to the standard, >> [...] > > ... is the first of your 2 examples really a user error? If so, it > breaks GotW #88: A Candidate For the “Most Important const” [1]. Can you > please clarify? > > Thanks in advance! > Olivier > > [1] > http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ >