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() {
        free(ptr);
        free(ptr2);
    }
}

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

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

Reply via email to