Lifetime bug in temporaries

Corey Kosak kosak@cs.cmu.edu
Wed Mar 25 07:58:00 GMT 1998


> Am I missing something, or is g++ lifetime of temporaries still not in
> tune with what it should be ?

I think choice (A).  The error in your code appears to be here:

template<class U, class V>inline Expr<SumExpr<Vector<U>, Vector<V> > >
operator+(const Vector<U> &a, const Vector<V> &b)
   {
   return make_expr(make_sum(a, b));
   }


the call to make_sum gives you a temporary that's going to disappear real soon
(i.e. at the semicolon), but unfortunately make_expr keeps a reference to it
anyway (stashing it away by passing it to the constructor for Expr.

Indeed, if you make the single-character edit from

template<class U>class Expr
   {
   const U &a;

...to...

   const U a;   // let's keep a copy rather than a reference


this appears to fix your immediate problem.



More information about the Gcc-bugs mailing list