Yigal Chripun wrote:
On 28/09/2009 12:05, Jeremie Pelletier wrote:
Nick Sabalausky wrote:
"Jeremie Pelletier" <jerem...@gmail.com> wrote in message
news:h9mmre$1i8...@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?

These aliases won't compile, and that was only one out of many union uses.

IMO the use cases for union are very rare and they all can be redesigned in a type safe manner.

Not always true.

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.

Again, that's a lazy view on programming. High level constructs are useful to isolate small and simple algorithms which are implemented at low level.

These aren't just marginal performance gains, they can easily be up to 15-30% improvements, sometimes 50% and more. If this is too complex or the risk is too high for you then don't use a systems language :)

Reply via email to