Null references redux

Yigal Chripun yigal100 at gmail.com
Mon Sep 28 06:06:54 PDT 2009


On 28/09/2009 12:05, Jeremie Pelletier wrote:
> Nick Sabalausky wrote:
>> "Jeremie Pelletier" <jeremiep at gmail.com> wrote in message
>> news:h9mmre$1i8j$1 at digitalmars.com...
>>> Ary Borenszweig wrote:
>>>> Object is not-nullable, Object? (or whatever syntax you like) is
>>>> nullable. So that line is a compile-time error: you can't cast a
>>>> null to an Object (because Object *can't* be null).
>>>>
>>> union A {
>>> Object foo;
>>> Object? bar;
>>> }
>>>
>>> Give me a type system, and I will find backdoors :)
>>>
>>
>> Unions are nothing more than an alternate syntax for a reinterpret
>> cast. And it's an arguably worse syntax because unlike casts, uses of
>> it are indistinguishable from normal safe code, there's nothing to
>> grep for. As such, unions should never be considered any more safe
>> than cast(x)y. The following is just as dangerous as your example
>> above and doesn't even touch the issue of nullability/non-nulability:
>>
>> union A {
>> int foo;
>> float bar;
>> }
>>
>
> Yet it's the only way I know of to do bitwise logic on floating points
> in D to extract the exponent, sign and mantissa for example.
>
> And yes they are much, much more than a simple reinterpret cast, a
> simple set of casts will not set the size of the union to its largest
> member. Unions make for elegant types which can have many valid
> representations:
>
> union Vec3F {
> struct { float x, y, z; }
> float[3] v;
> }
>
> I just can't picture D without unions :)

here's a type-safe alternative
note: untested

struct Vec3F {
   float[3] v;
   alias v[0] x;
   alias v[1] y;
   alias v[2] z;
}

D provides alignment control for structs, why do we need to have a 
separate union construct if it is just a special case of struct alignment?

IMO the use cases for union are very rare and they all can be redesigned 
in a type safe manner.
when software was small and simple, hand tuning code with low level 
mechanisms (such as unions and even using assembly) made a lot of sense. 
Today's software is typically far more complex and is way to big to risk 
loosing safety features for marginal performance gains.

micro optimizations simply doesn't scale.



More information about the Digitalmars-d mailing list