Topic: Temporary elimintation (was I need a language lawyer...)


Author: jamshid@ses.com (Jamshid Afshar)
Date: Mon, 22 Nov 1993 04:47:21 GMT
Raw View
In article <2a6n69$1c9@s.ms.uky.edu> jedwards@ms.uky.edu (Jonathan Edwards) writes:
>HugeInt operator-(const HugeInt& LHS,const HugeInt& RHS) {
>  HugeInt t = LHS;   // Assume HugeInt::HugeInt(const HugeInt&) exists
>  return (t -= RHS); // Assume HugeInt::operator-=(const HugeInt&) exists
>}
>is it legal for a C++ compiler to eliminate the variable t and the
>associated call to the copy constructor?

Has anyone noticed that the above is very different from:

 HugeInt operator-(const HugeInt& LHS,const HugeInt& RHS) {
    HugeInt t = LHS;
    t -= RHS;
    return t;
         }

A compiler can easily optimize away `t' in this function (see ARM 12
commentary), but it would be impossible to optimize away `t' in the
original version because the compiler doesn't "know" that

 HugeInt& HugeInt::operator-=();

returns `*this' (unless of course it was inline or the compiler did
inter-module analysis).  Therefore, the compiler would have to assume
the value being returned is not always the local variable `t'.  So, it
could not construct `t' directly into the "return value".

Fascinating, but it doesn't give me warm fuzzies knowing that the
latter version is typically faster than code which uses one less
statement.  Oh well, be carefull with overloaded operators -- what you
(think you) see is not necessarily what you get.

Jamshid Afshar
jamshid@ses.com