Memory safe in D

Lance Bachmeier no at spam.net
Tue Mar 12 18:32:59 UTC 2024


On Tuesday, 12 March 2024 at 17:53:41 UTC, Walter Bright wrote:
> On 3/12/2024 9:13 AM, Lance Bachmeier wrote:
>> 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.
>
> Should it be initialized to - what? Let's say you're creating a 
> linked list, with null signifying the end. If there aren't null 
> references, you're going to have to have an "end" marker or 
> some sort. So instead of checking for null, you have to check 
> for the marker. If you forget to check for the marker, and the 
> linked list goes off the end, then what? An exception is 
> thrown? An assert fail()? How are these better? The program 
> still fails at runtime.

I'm not sure I follow. As I understand it, `ExtraInfo extra;` and 
`ExtraInfo extra = null;` are exactly the same to the compiler 
(DMD generates identical assembly). My argument is that 
`ExtraInfo extra;` is confusing and therefore should not compile. 
That wouldn't restrict the language other than having to add 
"=null" to the declaration.



More information about the Digitalmars-d mailing list