jimad@microsoft.UUCP (Jim ADCOCK) (05/02/90)
How to do binary operators without a bunch of extra temporaries is sort
of a traditional problem in C++. I suspect Hanson's "C++ Answer Book:
covers this issue well, although I don't have a copy in front of me
to verify this.
Any time you explicetly new something, you must explicetly delete it.
The compiler will never introduce deletes for you.
In any case, I think your'e making life too hard on yourself.
Leaving everything else the same, try:
MemEater operator+(const MemEater& lm, const MemEater& rm)
{
MemEater sum;
for (int i=0; i<5000; ++i)
sum.a[i] = lm.a[i] + rm.a[i];
return sum;
}
On my machine, this results in the creation of four objects on the stack:
b, c, and d in main, and sum in op+. The only "sub-optimal" operations caused
by this approach is a loop to copy sum to d after the additions.
But on my machine, at least, the copy is accomplished using an optimal
single assembly instruction to move multiple words. Which in turn
takes 0.16uSec per element, or 0.8mSec to copy an entire 5000 element
array on my 486. So its not always obvious that an "extra copy"
represents any penalty. The copy may be fast enough to represent noise
compared to the other optimization choices a compiler has to make.