Out parameters and the strong exception guarantee

bearophile bearophileHUGS at lycos.com
Tue Jun 8 12:31:15 PDT 2010


Michel Fortin:

> But if one of your function has an 'out' parameter, it's impossible to 
> implement the strong guarantee, as illustrated by this trivial example:
> 
> 	void testOut(out int a) {
> 		throw new Exception("hello!");
> 	}
> 
> 	void main() {
> 		int a = 2;
> 		try
> 			testOut(a);
> 		finally
> 			writeln(a);
> 	}
> 
> Prints:
> 
> 	0
> 	object.Exception: hello!
> 
> This happens because the out parameter gets reset to its default value 
> as soon as you enter the function, so you can't throw an exception 
> before it has been changed.
> 
> So should 'out' be reformed to behave more like a return value? I'm not 
> sure. But I think this is something to keep in mind when using out 
> parameters.


In a recent post here:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=110908
and in some successive answers I have tried to explain that out arguments are a hack, they aren't as logically clean as multiple return values. I didn't think about exceptions too, your example adds one more case to what I was saying there. Thank you.

Bye,
bearophile


More information about the Digitalmars-d mailing list