D2.0: an example of use-case for casting invariant away

James Dennett jdennett at acm.org
Mon Jun 18 18:46:47 PDT 2007


Walter Bright wrote:
> Daniel Keep wrote:
>> Walter's said on a few occasions that the problem with C++'s const is
>> that casting away const is a *well-defined* operation.  That means that
>> const cannot be used to do any kind of optimisation, since it doesn't
>> really mean anything.
>>
>> The new page on const specifically states that casting away const or
>> invariance is *not* a well-defined operation, and you'd better know what
>> you're doing when you do it.
> 
> More specifically, in C++, you can cast away const-ness and then modify
> the underlying data, and this is defined to be legal, defined behavior.

More specifically still, in C++ you can cast away const-ness and then
modify the underlying object only if that underlying object is not
defined as being const.  If you modify an object that is actually
const (where I think Walter might say that it has const as it
"storage class", though that doesn't match C++ terminology) then
you have undefined behavior.

> With D, you can cast away const-ness, that is legal. But if you
> subsequently modify the underlying data, that is undefined behavior.

Seems reasonable to me (though one of C++'s faults is that it has
*too much* undefined behavior).

-- James



More information about the Digitalmars-d mailing list