Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's D's "out" storage class useful for?

Tags:

d

I know that out works pretty much like ref except that it initializes the passed argument to its default value upon entry into function.

My question is in what situation would this be useful "to reset a variable upon function entry"?

It would be great If someone could show me an example where out would be more useful than ref.

like image 594
Algo Avatar asked Dec 12 '22 04:12

Algo


1 Answers

The primary difference between ref and out is intention. When ref is used, it is expected that the value passed in will be used by the function. And the function may or may not set it. You can even have const ref if you want, which would mean that the variable which was passed in wouldn't be copied, but it couldn't be changed either.

const out, on the other hand, wouldn't make any sense, because the intention of out is that the variable will be set in the function. Using out is essentially a way to add another return value to the function. ref could be used for that, but using ref doesn't indicate to the caller that the value being passed in won't be used or even necessarily that the variable will be assigned to, whereas out indicates that the value will not be used and that the variable will be assigned to.

The reason that out sets the variable to its default value is to avoid bugs. If the purpose of the function is to use the out parameter as another return value, then you generally don't want that function to be affected by the value being passed in. By setting the out parameter to its default value, it guarantees that that variable will always be the same value for that function, regardless of what was passed in, so you avoid bugs caused by the function accidentally relying on that value.

Now, there is no requirement that an out parameter be assigned to within a function, but it does communicate to the caller that that's the intention, and it does assign it the default value regardless, so from the caller's perspective, an out parameter is always assigned a value (even if it's the default value). So, the function is free to not set the out parameter if that makes sense (e.g. if the default value was what should be "returned" under some set of circumstances).

like image 93
Jonathan M Davis Avatar answered Dec 30 '22 03:12

Jonathan M Davis