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

eao197 eao197 at intervale.ru
Thu Jun 21 01:59:54 PDT 2007


On Thu, 21 Jun 2007 11:32:53 +0400, Walter Bright  
<newshound1 at digitalmars.com> wrote:

> Don Clugston wrote:
>> 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.

May be it is better to define two new cast operators: const_cast, that  
removes only const, and invariant_cast, that removes only invariant.  
Ordinal cast() can't remove const/invariantness.

In such case Don Clugston's example will produce compile-time error  
(because cast() can't remove invariant). And all potentially dangerous  
places in a program can be easily detected by simply greeping  
/(const|invariant)_cast/


-- 
Regards,
Yauheni Akhotnikau



More information about the Digitalmars-d mailing list