auto init & what the code means

Daniel Gibson metalcaedes at gmail.com
Sun Dec 26 15:02:42 PST 2010


Am 26.12.2010 23:04, schrieb Jonathan M Davis:
> On Sunday 26 December 2010 07:08:22 Andrei Alexandrescu wrote:
>> On 12/26/10 8:54 AM, spir wrote:
>>> On Sun, 26 Dec 2010 14:54:12 +0100
>>>
>>> Andrej Mitrovic<andrej.mitrovich at gmail.com>   wrote:
>>>> int i;    // auto-initialized to int.init
>>>> int i = void; // not initialized
>>>
>>> Thanks. Actually this solves my "semantic" issue, did not even think at
>>> 'void'. (I will use it often). By the way, I don't want to play the
>>> superhero with uninitialised values, simply sometimes the initial value
>>> cannot be known at declare place.
>>>
>>> 	int i;
>>> 	if (foo)
>>> 	
>>> 	   i=0;
>>> 	
>>> 	else if (bar)
>>> 	
>>> 	   i=1;
>>> 	
>>> 	else
>>> 	
>>> 	   i=2;
>>> 	
>>> 	playWith(i);
>>
>> Problem with = void for elaborate types is that you need to use
>> emplace(&var, expr) to initialize them later.
>
> And of course the _big_  problem with = void is that you're dealing with garbage
> if you don't actually initialize the variable before you use it.

No, actually that's the *good* thing about = void. That initializing 
variables is default and you have this special syntax that may be used 
if you don't want initialization to happen.
I really like how D does this: Make the safe thing default and the 
unsafe thing possible via more typing.

> It's a good
> addition for performance-critical code, but in general, it's a _bad_ idea to
> use. It solves a major problem which exists in C and C++ with regards to
> undefined and undeterministic behavior. I'd get very worried if I started seeing
> code that used it all over the place.

Yes, definitely. It's good for optimization and should be only used 
there, so the places where it's used instantly catch your eye.

> There are straightforward cases where it's
> obvious that it's of benefit and obvious that the variable in question is being
> initialized, but beyond that, it really shouldn't be used.
>
> - Jonathan M Davis



More information about the Digitalmars-d mailing list