Proposal: Operator overloading without temporaries
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Tue Apr 4 13:00:10 PDT 2006
Don Clugston wrote:
> Bruno Medeiros wrote:
>> Don Clugston wrote:
>>> Background: Operator overloading, in the form it exists in C++ and
>>> currently in D, inherently results in sub-optimal code, because it
>>> always results in unnecessary temporary objects being created.
>>>
>>> For example,
>>> X = A - ((B*C) + D)* E;
>>>
>>> becomes:
>>> T1 = B * C;
>>> T2 = T1 + D;
>>> T3 = T2 * E;
>>> T4 = A - T3;
>>> X = T4;
>>> Four objects were created, whereas only one was strictly required.
>>
>> Ok, I'm new to this, so it took me a while to understand the problem.
>> Let's see if I got it right: this is actually only a problem when the
>> operator methods explicitly instantiate a *class object*, to be used
>> as the return of the method, right?
>
> Not really, it applies everywhere that you can have overloaded
> operators. The cost of a temporary will be greater with classes, but for
> structs, eliminating temporaries will make it much easier for the
> compiler to optimise.
>
But with structs (more generally, with stack-based value types), can't
the compiler already optimize it? In your example, it seems to me that
the compiler make the code so that it uses only two temporaries:
T1 = B * C;
T2 = T1 + D; // T1 is now free for use
T1 = T2 * E; // T2 is now free for use
T2 = A - T1; // T1 is now free for use
X = T2;
And, if inlining occurs, it can be made to use only one temporary, no?
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list