Casting away const

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 9 08:53:24 PDT 2010


On Mon, 09 Aug 2010 11:31:18 -0400, Simen kjaeraas  
<simen.kjaras at gmail.com> wrote:

> 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.
>

The compiler will rewrite the code as follows:

return cache.opEquals(-1) ? cache.opAssign(_expensiveFunctionImpl()) :  
cache.xxx;

I'm assuming for cache.xxx that it's some sort of alias this to a getter  
function.  All of these function would be const.

We can define the opAssign in such a way that it cannot be inlined,  
forcing the compiler to assume nothing about the result of opAssign.

Note also that the optimization you stated is not possible, even without  
casting away const, but would be possible on an immutable class.  But the  
fact that the compiler cannot peek into the implementation of the opAssign  
means it's forced to make no assumptions about the result of opAssign.

How does one write a conforming compiler that alters the result of this?

-Steve


More information about the Digitalmars-d-learn mailing list