scope(exit) considered harmful

Justin Johansson no at spam.com
Sun Nov 8 11:23:44 PST 2009


dsimcha 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.

I know what you mean, but it's not like "D" stands for "Discovered America".
scope(exit) is just some syntactic sugar which stack allocated objects in C++
have been able to do since Bjarne Stroustrup (C++ inventor) was in knee-high
locks, umm, socks :-)

class Lock
{
  Foo foo;

  Lock( Foo aFoo): foo( aFoo) {
   // lock Foo resource
   lock( foo);
 }

  ~Lock() {
  // unlock Foo resource
   unlock( foo);
  }
}


void myFunc( Foo foo)
{
  Lock( foo);

  // do something with the locked resource
  // that might throw an exception
  // ... processing()

  // Note that the Foo resource is acquired and
  // upon entry to this function and released
  // when the function scope exits irrespective
  // of whether an exception is thown by
  // processing() or not.
}

No sign of any ugly try/finally here; yet achieves safe outcome.

C++ constructors/destructors and stack-unwinding mechanism
are considered FREAKING AWESOME.

-- Justin :-)




More information about the Digitalmars-d mailing list