[LC++]Return values vs reference parameters

Mark Phillips mark at austrics.com.au
Fri Jul 27 18:55:08 UTC 2001


Suppose I want to be able to take two arrays (vector<int>)
and do a position-by-position multiply of the entries to
produce a new array.  Ie the following:

int const N=100;
..... insert definition of a class "arrayTy" which
      implements arrays of fixed size N .....

void doPointwiseMult(arrayTy& w, arrayTy const& u, arrayTy const& v) {
  int i;
  for (i=0; i<N; i++)
    w[i]=u[i]*v[i];
}

Then do
  doPointwiseMult(w, u, v);

Now this will do the job quite efficiently, but syntactically is ugly.
The
following improves the syntax.

arrayTy pointwiseMult(arrayTy const& u, arrayTy const& v) {
  int i;
  arrayTy tmpArray;
  for (i=0; i<N; i++)
    tmpArray[i]=u[i]*v[i];
  return tmpArray;
}

then you can write
  w=pointwiseMult(u, v);

which is syntactically a bit nicer.  Even better, the above function can

be turned into an overloading of operator*, which means you could write:

  w=u*v;

This is really nice syntactically, but is rather inefficient.  It
involves
the creation of two temporary arrayTy variables, and requires both
the copy constructor and the assignment operator to be called.  Whereas
the first approach I gave doesn't need any of this!!!!

There is a huge price of computational inefficiencies in order to get
syntactically nice code.  Surely this is not the C++ way?  Are there
ways and means to get around these problems?

I've heard of "return value optimization", but this seems to only
partially solve these issues, and currently seems not to be well
implemented.

Any thoughts?

Cheers,

Mark.





More information about the tuxCPProgramming mailing list