D2.0: an example of use-case for casting invariant away
Don Clugston
dac at nospam.com.au
Thu Jun 21 00:25:43 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.
>
> With D, you can cast away const-ness, that is legal. But if you
> subsequently modify the underlying data, that is undefined behavior.
It sounds that in D, it will be too easy to cast away constness accidentally.
With C++, at least you can grep for const_cast and detect potentially dangerous
code, and you get a strong visual clue.
Suppose I've written a D function like this:
void f(int *b, uint c)
{
// maybe I'm avoiding a compiler warning or something.
uint *d = cast(uint *)b;
d += c;
}
Months later, I'm refactoring the code, and I convert the int * parameter to an
invariant, without recognising that it's changing the value of b. Oops.
C++'s const would catch this mistake, but if I understand correctly, D will
compile it without error. Suddenly the function has moved into the realm of
undefined behaviour.
I hope I'm wrong. Or did I miss something?
More information about the Digitalmars-d
mailing list