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

Don Clugston dac at nospam.com.au
Thu Jun 21 01:40:42 PDT 2007


Walter Bright wrote:
> Don Clugston wrote:
>> Walter Bright wrote:
>>> 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?
> 
> No, you're not missing something. It is a general problem with cast - 
> cast is a blunt instrument which can easily hide problems.

This means that cast() has just become even more unsafe. So for 2.0, it will be 
even more important to provide ways to avoid usage of cast().
The .ptr, .re, and .im properties were a huge help; maybe the idea can be 
extended to other cases where a cast is perfectly safe.

Usage of invariants inside unions is suspect too.
At least where some members are invariant and others are not const, it's asking 
for trouble -- cast() by stealth.

union U {
  invariant C *c;
  C *d;
}
Though arguably unions are always a blunt, dangerous instrument as well.



More information about the Digitalmars-d mailing list