What does assigning void mean?
Simen Kjærås
simen.kjaras at gmail.com
Thu Mar 5 09:04:07 UTC 2020
On Thursday, 5 March 2020 at 08:35:52 UTC, drug wrote:
> On 3/5/20 10:47 AM, mark wrote:
>> In Adam Ruppe's D Cookbook there're these lines in a ref
>> counting example:
>>
>> RefCountedObject o = void; // What does this mean/do?
>> o.data = new Implementation();
>> o.data.refcount = 1;
>>
>> I don't understand the first line; could someone explain
>> please?
>
>
> In D all vars are initialized by default. If you use assigning
> void then the var won't be initialized.
To expand a bit on this: You probably don't want to initialize
things with = void - it can lead to hard-to-track bugs and
unexpected behavior. The reasons it's there is almost entirely as
an optimization - if you know the variable will be initialized
elsewhere void initialization ensure things won't be initialized
twice when once is enough, and this can be faster.
The other use case is when for whatever reason there is no valid
default value, but you still want an instance. Probably in order
to fill it with data from somewhere else. This would apply e.g.
to structs with @disabled parameterless constructors whose
contents you are reading from disk.
In short, when you know you need to void initialize something,
that's when you're ready to use it. Kinda like goto.
--
Simen
More information about the Digitalmars-d-learn
mailing list