Out parameters and the strong exception guarantee

Michel Fortin michel.fortin at michelf.com
Tue Jun 8 05:28:42 PDT 2010


The strong exception guarantee guaranties that if an exception is 
thrown, the function will have no side effect. Of course, not all 
function can support this (a file I/O error in the middle of writing 
will have side effects), but often it can and it's generally good 
practice to offer the guaranty whenever possible.
<http://en.wikipedia.org/wiki/Exception_guarantees>

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.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list