Casting away const

Steven Schveighoffer schveiguy at yahoo.com
Mon Aug 9 07:35:02 PDT 2010


On Mon, 09 Aug 2010 10:27:09 -0400, Don <nospam at nospam.com> wrote:

> Steven Schveighoffer wrote:
>> On Mon, 09 Aug 2010 09:57:47 -0400, bearophile  
>> <bearophileHUGS at lycos.com> wrote:
>>
>>> Steven Schveighoffer:
>>>> I thought it was "you're on your own", not undefined behavior.  The  
>>>> former
>>>> implies there is some "right" way to do this if you know more about  
>>>> the
>>>> data than the compiler, the latter implies that there is no right way  
>>>> to
>>>> cast away const.  Am I wrong?
>>>
>>> In my opinion if this thing is well designed then you go in undefined  
>>> behaviour only when you change the contents of something after you  
>>> have removed its const nature with a cast. Just casting const away and  
>>> then reading the data can't be undefined behaviour, otherwise casting  
>>> const away is useless and can be totally disallowed.
>>  Casting away const just to read the data is useless.  You can read  
>> const data without a cast.
>
> No you can't. You can't pass it to a C function.

Sure you can.

extern(C) int strlen(const(char) *arg);

>
>>  But my understanding is that casting away const to write should be  
>> doable if you know what you're doing.  If this is undefined behavior,  
>> then that's fine, I'm just unclear on what "undefined behavior"  
>> actually means.  I thought "undefined behavior" means that you cannot  
>> count on the behavior to work in the future.
>>  An example of where casting away const to write should be allowed is  
>> for a hypothetical mutable member:
>>  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.

-Steve


More information about the Digitalmars-d-learn mailing list