On Tuesday, 12 March 2024 at 03:12:44 UTC, Walter Bright wrote:
> The default value for a class reference is null
. Most objects need an "I'm not a valid object" value, and null is ideal for it because if it is dereferenced, a hardware segment fault is generated.
If a variable is initialized with void
, that is something completely different. The variable winds up being set to garbage, as it is not initialized at all. This is why void
initialization for references is only allowed in code marked @safe, and is usually used when top efficiency is required.
Consider what a null class reference is good for:
class ExtraInfo { ... }
struct S
{
int a,b,c;
ExtraInfo extra;
}
In my program, sometimes I need the extra
info, but most of the time, not. Why have the compiler force an allocation for extra
if it isn't used all the time? That just wastes time and memory.
You can write ExtraInfo extra = null;
.
The reason ExtraInfo extra;
is so confusing, and leads to posts like the one that started this thread, is because you're explicitly telling the compiler you want ExtraInfo. A new user of the language has no reason to expect it to be null. Someone wanting to optimize their code should have to be explicit that they want null and they're willing to deal with all the problems that can cause.
While it's true that your program is always going to crash, that's not a great solution unless you're testing every possible outcome for your program as you write it. It can take a long time for it to crash, possibly when you're busy with other things, and with no indication of why it crashed.