Possible way to achieve lazy loading with const objects

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 29 11:11:46 PDT 2011


On Thu, 29 Sep 2011 13:41:04 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> On 9/29/11 10:39 AM, Steven Schveighoffer wrote:
>> Compare changing opEquals to const instead of just *adding* a const
>> version of opEquals. With a straight change, the code doesn't compile
>> and you put const on opEquals wherever it complains. Now it's still
>> fully defined and runs the same as before. How is that a bad thing?
>
> It's a bad thing because it breaks existing code.

But not *silently*.  Breaking existing code is a tradeoff.  I contend that  
the tradeoff is worth it, because:

1. 99% of the cases where opEquals is not const can just be switched to  
const (i.e. the code runs fine as const, but must not be labeled const  
because of the current language defect).  For these cases, the break is  
trivial to fix.
2. Any place where opEquals actually *does* modify the object are either  
abusing opEquals (i.e. actually changing state) and should be rewritten,  
or enabling an optimization (i.e. caching).

So the change *promotes* doing the right thing (switching opEquals to  
const) in cases where it's a trivial change.

The optimization is the only legitimate counter-case.  However, we should  
make that version the exception, since it is not common (and is not  
technically necessary).  Most opEquals are like what I have written --  
compare each member.

So how do we solve the optimization?  I think this is better solved by  
solving the logical const problem in general rather than infect every  
object which does not care about it with the burden of defining multiple  
opEquals'.

Note that I think the compiler should not care at all about opEquals'  
definition for structs.

-Steve


More information about the Digitalmars-d mailing list