scope(exit) without exception handling?
Steven Schveighoffer
schveiguy at yahoo.com
Wed May 16 06:10:05 PDT 2012
On Tue, 15 May 2012 23:54:04 -0400, Mehrdad <wfunction at hotmail.com> wrote:
> I'm writing some (low-level) code with no exception handling available
> whatsoever... either the code runs, or it doesn't.
>
> Is there any way for me to use scope(exit) (or perhaps a destructor,
> like RAII) to mean, "Execute this block of code for me when the block is
> exited, will ya?", *without* introducing dependencies on exception
> handling?
struct AddExitBlock
{
private void delegate() dg;
this(scope void delegate() dg) {this.dg = dg;}
~this() {dg();}
}
void main()
{
int x = 0;
{
x = 1;
immutable _aeb = AddExitBlock({x = 0;}); // annoying to have to
assign it to a temporary variable, but whatever.
assert(x == 1);
}
assert(x == 0);
}
Also seems to work with exceptions (if you need them):
void foo(ref int x)
{
x = 1;
immutable aeb1 = AddExitBlock({x = 0;});
throw new Exception("testing!");
}
void main()
{
int x = 0;
try
{
foo(x);
}
catch(Exception e)
{
}
assert(x == 0);
}
I don't see exception handling in the generated code (at least I don't see
the _d_local_unwind2), I wonder a) if this is more efficient than
scope(exit), and b) if so, why can't the compiler do this automatically?
-Steve
More information about the Digitalmars-d
mailing list