What is going on here?

w0rp via Digitalmars-d digitalmars-d at puremagic.com
Sat Mar 7 13:44:56 PST 2015

Why not handle the scope(failure) cases in the constructor itself?

struct SomeStruct {
     void* ptr;
     void* ptr2;

     this() {
         ptr = malloc(...);
         scope(failure) free(ptr);

         /* Whatever follows, possibly throwing. */

         ptr2 = malloc(...);
         scope(failure) free(ptr2);

     ~this() {

Now if the constructor throws, the resource which needs to be 
dealt with, whatever it is, is handled even though the destructor 
is never invoked. Additionally, you only execute the 
scope(failure) lines you reach before an exception is thrown, 
whereas the destructor will try to clean up all of the resources. 
Now the user of SomeStruct can use it the RAII way, and never 
have to worry about handling cleanup for it.

Then you can use the some simple rules and apply them 

1. Declare constructors as nothrow where you can.
2. Handle failure cases when you can't declare constructors as 

More information about the Digitalmars-d mailing list