Why does scope(success) have to use exceptions?
Maxim Fomin
maxim at maxim-fomin.ru
Thu Jan 17 04:15:06 PST 2013
On Wednesday, 16 January 2013 at 23:19:20 UTC, Andrej Mitrovic
wrote:
> Sample code:
>
> void callScope(ref int x)
> {
> x = 1;
> scope(success) { x = 2; }
> x = 3;
> scope(success) { x = 4; }
> }
>
> void callFunc(ref int x)
> {
> x = 1;
> x = 3;
> x = 4;
> x = 2;
> }
>
> void main()
> {
> int x;
> callScope(x);
> assert(x == 2);
>
> callFunc(x);
> assert(x == 2);
> }
>
> I was expecting callScope to be lowered down to the handwritten
> code
> in callFunc in assembly, but instead it uses exceptions. Here's
> some
> simple ASM for callFunc compiled with -c -release -O (no
> inline):
>
> I'm trying to understand why. If an exception is thrown between
> one of
> those assignment statements the stack will unwind and any
> following
> assignment statements will not be called, so there shouldn't be
> a need
> to check if an exception is thrown. Why doesn't the compiler
> simply
> rewrite callScope to look like callFunc?
On linux, segfaults can be translated into exceptions using this
module
(https://github.com/D-Programming-Language/druntime/blob/master/src/etc/linux/memoryerror.d)
however I do not know how to use it - I get linker errors.
On windows null pointer errors are translated into Object.Error
(Access Violation) - I do not remember exactly.
In any case, your void callScope(ref int x) can be blown up by:
int* ptr; callScope(*ptr); so, exceptions may come when they are
not expected.
More information about the Digitalmars-d
mailing list