Sense check: construction / deconstruction

Jordan Wilson wilsonjord at gmail.com
Tue Apr 24 22:59:33 UTC 2018


I have the following code:
import std.stdio;
import std.typecons;
import d2sqlite3;

class A {
     Database db;
     this ( Database d) {
         db = d;
     }
}

class B {
     Database* db;
     this ( Database* d) {
         db = d;
     }
}

void main() {
     auto db = Database(":memory:");
     auto a = new A(db); // gives message:
                         // Error: clean-up of Database incorrectly
                         // depends on destructors called by the GC

     auto b = new B(&db); // no message
     auto c = scoped!A(db); // no message
}

Assumption 1: "a" gives me an error message due to the fact that 
proper clean up of db depends on a being collected by the GC, and 
this behavior is being dis-allowed through use of the idiom 
https://p0nce.github.io/d-idioms/#GC-proof-resource-class?
The relevant function calling the error message is:
void ensureNotInGC(T)(string info = null) nothrow
{
     import core.exception : InvalidMemoryOperationError;
     try
     {
         import core.memory : GC;
         cast(void) GC.malloc(1);
         return;
     }
     catch(InvalidMemoryOperationError e)
     {
         // error message here
     }
}

Assumption 2: "b" gives me no error messages because the class B 
uses pointers, which moves it from relying on GC, to being 
manually free?

Assumption 3: "c" gives me no error messages because...well, I 
don't really understand why, maybe because c is in the same scope 
as db?

Thanks,

Jordan


More information about the Digitalmars-d-learn mailing list