On 3/31/15 11:23 AM, Adam D. Ruppe wrote:
On Tuesday, 31 March 2015 at 15:12:54 UTC, ref2401 wrote:
Could anyone describe me what this initialization does, please?

It skips the initialization entirely, leaving the memory random instead
of making it zeroes (or NaN or whatever the .init is of the actual type,
typically zero though).

The struct members will thus be random when made with =void. However, it
does tell the compiler that you thought about initializing it - you tell
it you specifically want it uniniitalized and didn't just forget to
write something.

When do I need to use the void initialization?

Very rarely, don't use it unless you can answer this yourself.

But some possible answers would be:

1) the initialization wasted program runtime; it can be an optimization.
Only use it in this case if you are sure it matters (the speed was
actually a problem) and if you do initialize it yourself immediately
afterward. Otherwise, you might be introducing bugs.

2) you want some kind of random data, like if you are using it to seed a
random number. There's often better ways of doing this, but =void might
work in some cases.

Stack data is almost never random. I'd also substitute "often" for "always".


3) You are initializing a private member with default construction
turned off. Here, "Struct s;" wouldn't compile because of the disabled
default constructor, but you need to set it up anyway. So you do "Struct
s = void; s.values = something;" - void to tell the compiler you know
what you're doing, then you quickly initialize it to what it needs to
be.  I say in a private member because you'd be bypassing the object's
requirements this way, so you are responsibile for making sure the
values are indeed valid before using the object.

4) initialization depends on runtime logic, but you want to scope the variable outside those conditionals. For example:

Struct s = void;

if(somecond)
{
   s = option1;
}
else
{
   s = option2;
}

// need to use s out here

Of course, this is a ridiculous example, a real example would be more complex (generally your logic is difficult to rework coupled with other code). This doesn't happen very often, but it is really the only time I have used the =void expression.

-Steve

Reply via email to