scope(exit) considered harmful

Bill Baxter wbaxter at gmail.com
Sun Nov 8 09:17:53 PST 2009


On Sun, Nov 8, 2009 at 8:12 AM, dsimcha <dsimcha at yahoo.com> wrote:
> Hey, I never programmed at all seriously in C++ before coming to D and I somehow
> figured out scope(exit).  I'm not even sure you'd be able to pry scope(exit) out
> of my cold, dead hands.  I might super-glue it to my hands on my death bed.
>
> Example of where you could do stuff with scope statements that would be **almost
> impossible** with try/catch/finally:
>
> enum myConvenientMixin =
> q{
>    myRegionAllocator.init();
>    scope(exit) myRegionAllocator.destroy();
> };
>
> void someFunction() {
>    mixin(myConvenientMixin);
>
>    // Build some really complicated data structure using
>    // myRegionAllocator.
> }
>
> With finally only, myRegionAllocator would be so horribly ugly to use in the
> presence of throwing code that noone would ever even consider doing such a thing.
>  With scope(exit) and mixins, you've solved the problem of the memory getting
> freed in one line of code and don't even need to think about it when writing the
> rest of your function.

Well, in C++ you'd probably wrap up myRegionAllocator in a struct and
put the .destroy call in its destructor.  For use you'd put an
instance of the struct on the stack.  But scope(exit) is much more
convenient than having to put all your cleanup code into a struct.

--bb



More information about the Digitalmars-d mailing list