Null references redux

Jeremie Pelletier jeremiep at gmail.com
Mon Sep 28 03:05:45 PDT 2009


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 :)



More information about the Digitalmars-d mailing list