Memory safe in D

Walter Bright newshound2 at digitalmars.com
Tue Mar 12 03:12:44 UTC 2024


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:

```D
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.


More information about the Digitalmars-d mailing list