Proposal: Operator overloading without temporaries

Don Clugston dac at nospam.com.au
Wed Apr 5 01:59:05 PDT 2006


Bruno Medeiros wrote:
> 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;

True, but for objects on the stack, the cost is really just in the 
copying of data, not the memory allocation. T1 and T2 still get 
initialised twice.

> And, if inlining occurs, it can be made to use only one temporary, no?

Indeed, the compiler might optimise it, if the structs are small enough. 
Which is why I said that it makes it "much easier for the compiler to 
optimise". It might be able to do it without this help, but my 
experience with C++ has been that inlining is unreliable.





More information about the Digitalmars-d mailing list