Casting away const

Simen kjaeraas simen.kjaras at gmail.com
Mon Aug 9 08:31:18 PDT 2010


Steven Schveighoffer <schveiguy at yahoo.com> wrote:

>>>  class C
>>> {
>>>    private Mutable!(int) cache = -1;
>>>    int expensiveFunction() const { return cache == -1 ? cache =  
>>> _expensiveFunctionImpl() : cache; }
>>>    private int _expensiveFunctionImpl() const {...}
>>> }
>>>  If this is undefined, then something like this cannot be relied on,  
>>> even when performance is critical.
>>>  -Steve
>>
>> I really can't see how the compiler could make that work, without  
>> destroying most of the benefits of const. For example, if that code is  
>> legal, it disallows most const-related optimisation.
>
> Why not?  What possible optimization can the compiler do here?  Mutable  
> has an assign operation that is labeled as const, it should be callable  
> by the compiler.
>
> I haven't really seen what const optimizations can be, so maybe an  
> example (even if unimplemented) is helpful.

The compiler may decide to store the value of cache in a register, and
use that value instead of fetching it after _expensiveFunctionImpl is
called. That's the simplest example I could come up with.

-- 
Simen


More information about the Digitalmars-d-learn mailing list