Struct field destructor not called when exception is thrown in the main struct destructor

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 16 16:05:47 UTC 2020


On 10/16/20 11:11 AM, Ali Çehreli wrote:
> On 10/16/20 6:12 AM, tchaloupka wrote:
> 
>  > struct Foo {
>  >      Bar bar;
>  >      bool err;
>  >
>  >      ~this() {
>  >          // scope(failure) destroy(bar); // < this fixes the Bar
>  > destructor call
>  >          enforce(!err, "Test err");
> 
> Well, that check means "cannot continue", which means the compiler stops 
> executing the destruction code because it can't. (It would a serious bug 
> if it continued execution in a state that the program knows to be invalid.)

The destruction of members is outside the destructor's purview. It can't 
turn the destruction off, so it should logically be considered part of 
an enclosing function.

Note that enforce is throwing an *Exception*, not an *Error*, it does 
not mean the program is in an invalid state. Throwing an Error, the 
compiler is allowed to not clean up after itself.

Imagine if throwing an Exception disabled RAII in any enclosing function 
scopes because it considered that an invalid state.

> Conceptually, bar's destructor is called on that closing brace but we 
> decided to abort mission earlier. Your calling destroy(bar) may or may 
> not be wrong in case of 'err'. Only you know at that point.

If that is the case, a hand written destructor should turn off automatic 
destruction of members. Either the compiler handles member destruction 
or it doesn't.

-Steve


More information about the Digitalmars-d-learn mailing list