D Best Practices: Default initializers for structs

d'oh homer at simpsons.name
Sun Nov 7 05:41:36 PST 2010


On 07/11/10 15:28, Jonathan M Davis wrote:
> Here's an interesting thought. All built-in types in D default initialize to the
> closest thing that they have to an error. Floating points arguably do the best
> job of this with NAN, and integral types arguably the worst with 0, but that is,
> as I understand it, the basic idea: default initializations initialize to an
> error value (or as close to one as you can get). That way, it quickly becomes
> obvious when you failed to properly initialize one before using it. So, the
> question is this: what about structs?
>
> Structs default initialize to whatever their member variables are directly
> initialized to. That may or may not be an error state, but I don't get the
> impression that people generally _try_ and make it an error state. What should
> be the best practice on this? Should we generally _try_ and make struct
> initializers initialize to error states, just like the primitive types do - with
> the idea that you really are supposed to initialize them or assign to them
> before you use them. Or should we treat structs differently and try and make
> their default states something other than an error state?
>
> By no means am I claiming that we should _always_ try and make a struct's init
> property an error or _always_ make it valid (that's going to depend on what
> exactly the struct is for and what it does), but which would be the best
> practice in the general case?
>
> - Jonathan M Davis

Arguable floating points would do better with -Infinity and integral 
types with a negative value e.g. -1, -2 or as negative as possible.
I suspect booleans would do better with true (this being the furtherest
away from false .. that if is false is taken to be the origin of the
boolean value axis).

Zero for an INIT value for integral types doesn't make sense for an 
"error" value in terms of least frequency of encounter.

All-in-all, and for fast fail, the one simple rule that is easy to 
remember would be "all bits set" and that's all folks.

I leave this as an exercise for the reader to speculate on what 
all-bits-set might manifest as at runtime for uninitialized pointers, in 
particular re null pointer exceptions.

Remember Occam's Razor


More information about the Digitalmars-d mailing list