[comp.lang.c++] proposed NRV syntax change

bart@videovax.tv.Tek.com (Bart Massey) (08/10/89)

My biggest beef with NRVs is that I've used them in Pascal and really hated
them there -- it's really nice for the compiler to be able to warn you that
your function may fall off the end without returning a value, and most
Pascal compilers aren't that smart.  It just so happens that I'm the only
programmer in the world dumb enough to forget to return a value from a
function, but... :-) :-)

Of course, as Doug Lea commented, the situation is different in C++, where
you will return something that is properly constructed instead of random
garbage if you fall off the end by accident.  But it's not clear that this
is better from a correctness point of view -- the compiler now has no idea
whether you meant to fall off the end or not, and thus *should not* warn
about it.  In fact, it's worse than that, since you may have altered the
object but left it in the "wrong" state before falling off.

I guess I've always sort of thought of the C/lint requirement of an explicit
return value at end-of-function as an assertion that I, the programmer,
haven't forgotten about that important case, and kind of liked it for that
reason.  NRVs as currently implemented seem to me to break that model.

I guess what I would like is to allow NRVs, but still require the explicit
return statement.  If the return value happens to be the NRV, then the
compiler may optimize that case.  Any other return value is treated as
usual.  To use Doug Lea's example,

X iota_nrv() return x          // x is the name of the X we may be returning
{
  if( Xsize == -1 ) {	       // some special case
      X *y;
      magic_construct( y );    // some magic construction
      return *y;                // return a copy via X(X&)
  }
  for (int i=0; i<Xsize; ++i)  // fill it up & get out
     x.set(i, i); 	       // the NRV is special
  return x;		       // and doesn't need to be copied and constructed
}


This has at least three important benefits, the first of which I've already
talked about.  The second is illustrated by the special case above.  The
third is that one can trivially convert the above code for a C++ compiler
which doesn't support NRVs, at some loss in efficiency, since the function
body proper may remain identical.

If the special case above were too much trouble, I would be satisfied with
specifying that all returns from a function with NRV "x" would be of the form
"return x;", and this would still provide the other two benefits mentioned
above.

No flames please!  If I've obviously bungled, please wait a few days for
someone else to correct me first :-).  But questions and comments are
welcome, and I'd be glad to summarize any e-mail I get.

					Bart Massey
					..tektronix!videovax.tv.tek.com!bart